题解 | #判断两个IP是否属于同一子网#

判断两个IP是否属于同一子网

https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218

#include <iostream>
#include <vector>
#include <string>
using namespace std;

long long str2int(string str){
    vector<int> a(4,0);
        int point = 0;
        for(int i = 0; i < str.size(); i++){
            if(str[i] != '.')
                a[point] = a[point]*10+(str[i]-'0');
            else{
                //cout << a[point] << endl;
                point++;
            }
                
        }
        /*for(int i = 0; i < 4; i++){
            cout << a[i] << endl;
        }*/
        long long int res = (a[0] <<24) + (a[1] <<16) + (a[2] <<8) + a[3];
        return res;
}

bool ipValid(string str){
    vector<int> a(4,0);
        int point = 0;
        for(int i = 0; i < str.size(); i++){
            if(str[i] != '.')
                a[point] = a[point]*10+(str[i]-'0');
            else{
                //cout << a[point] << endl;
                point++;
            }
                
        }

        for(int i = 0; i < 4; i++){
            if(a[i] > 255 || a[i] < 0)
                return false;
        }

        return true;
}

bool maskValid(string str){
    vector<int> a(4,0);
        int point = 0;
        for(int i = 0; i < str.size(); i++){
            if(str[i] != '.')
                a[point] = a[point]*10+(str[i]-'0');
            else{
                //cout << a[point] << endl;
                point++;
            }
                
        }

        for(int i = 0; i < 3; i++){
            if(a[i] <255 && a[i+1] > 0)
                return false;
        }

        return true;
}

int main() {
    string str1, ip1, ip2;
    while (cin >> str1 >> ip1 >> ip2) { // 注意 while 处理多个 case
        long long mask = str2int(str1);
        long long ip1_int = str2int(ip1);
        long long ip2_int = str2int(ip2);
        long long tmp = mask;
        while( (mask& 1) == 0 && mask != 0) mask = mask >> 1;
        if((mask & (mask+1)) != 0 || !(ipValid(ip1) || !(ipValid(ip2))) || tmp == 0 || !(maskValid(str1))) {
            cout << 1 << endl; 
            
        }else{
           long long and1 = tmp & ip1_int;
           long long and2 = tmp & ip2_int;
           //cout << and1 << ' ' << and2 << endl;
           if(and1 == and2)
                cout << 0 << endl;
            else
                cout << 2 << endl;
        }
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务