【九度OJ】1203:IP地址

地址:
http://ac.jobdu.com/problem.php?pid=1203
題目描述:
輸入一個ip地址串,判斷是否合法。
輸入:
輸入的第一行包括一個整數n(1<=n<=500),代表下面會出現的IP地址的個數。
接下來的n行每行有一個IP地址,IP地址的形式爲a.b.c.d,其中a、b、c、d都是整數。
輸出:
可能有多組測試數據,對於每組數據,如果IP地址合法則輸出”Yes!”,否則輸出”No!”。
樣例輸入:
2
255.255.255.255
512.12.2.3
樣例輸出:
Yes!
No!
提示:
合法的IP地址爲:
a、b、c、d都是0-255的整數。
來源:
2006年華中科技大學計算機保研機試真題

解題思路:
沒有想比較巧妙的方法,直接懟,先找出點的位置,再根據3個點的位置算出4個整數,並在此過程中對於一些違法的輸入進行判斷,比方說字符串長度超過15,輸入除了’.’和數字字符的其他字符,輸入了超過3個點,點之間的整數不在範圍0-255之間,都說明這個字符串不是ip地址。

源碼:

#include<stdio.h>
#include<string.h>
 
int n;
int ipLen;
char ipAddress[ 20 ];
 
int main(){
    scanf( "%d", &n );
    while( n-- ){
        scanf( "%s", &ipAddress );
 
        int isIp = 1;
        ipLen = strlen( ipAddress );
        //判斷字符串是不是ip地址
        if( ipLen > 15 ){   //字符串長度超過15,該字符串就不可能是ip地址
            printf("No!\n");
            continue;
        }
 
        //遍歷字符串,查找點的位置,如果點的個數超過3個,輸出No!
        //如果字符串中除了'.'之外還有不是數字的字符,輸出No!
        int pointIndex[ 3 ];
        int countPoint = 0;
        for( int i = 0; i < ipLen; i ++ ){
            if( ipAddress[ i ] == '.' ){
                pointIndex[ countPoint ] = i;
                countPoint ++;
 
                if( countPoint > 3){
                    isIp = 0;
                    break;
                }
            }
            else if( ipAddress[ i ] < '0' || ipAddress[ i ] > '9' ){
                isIp = 0;
                break;
            }
        }
 
        if( isIp == 0 ){
            printf("No!\n");
            continue;
        }
 
        int a = 0;
        for( int i = 0; i < pointIndex[ 0 ]; i ++ ){
            a = a * 10 + (int)(ipAddress[i] - '0');
        }
        if( a < 0 || a > 255 ){
            printf("No!\n");
            continue;
        }
        a = 0;
        for( int i = pointIndex[ 0 ] + 1; i < pointIndex[ 1 ]; i ++ ){
            a = a * 10 + (int)(ipAddress[i] - '0');
        }
        if( a < 0 || a > 255 ){
            printf("No!\n");
            continue;
        }
        a = 0;
        for( int i = pointIndex[ 1 ] + 1; i < pointIndex[ 2 ]; i ++ ){
            a = a * 10 + (int)(ipAddress[i] - '0');
        }
        if( a < 0 || a > 255 ){
            printf("No!\n");
            continue;
        }
        a = 0;
        for( int i = pointIndex[ 2 ] + 1; i < ipLen; i ++ ){
            a = a * 10 + (int)(ipAddress[i] - '0');
        }
        if( a < 0 || a > 255 ){
            printf("No!\n");
            continue;
        }
 
        printf("Yes!\n");
    }
 
    return 0;
}
/**************************************************************
    Problem: 1203
    User: 螺小旋
    Language: C++
    Result: Accepted
    Time:0 ms
    Memory:1020 kb
****************************************************************/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章