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

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

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

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

bool isValidIP(vector<unsigned int>& IP){
    if(IP.size() != 4){
        return false;
    }
    for(auto num : IP){
        if(num > 255){
            return false;
        }
    }
    return true;
}

bool isValidMask(vector<unsigned int>& mask){
    if(!isValidIP(mask)){
        return false;
    }
    unsigned int decimal = 0;
    for(int i = 0; i < mask.size(); ++i){
        decimal += mask[i] * pow(2, 24-8*i); 
    }
    decimal = ~decimal;
    decimal += 1;
    int cnt = 0;
    while(decimal){
        if(decimal & 1){
            ++cnt;
        }
        decimal >>= 1;
    }
    return cnt == 1 ? true : false;

}

void processor(string& str, vector<unsigned int>& res){
    int start = 0;
    for(int end = start; end < str.size(); ++end){
        if(str[end] == '.'){
            res.push_back((unsigned int)stoi(str.substr(start, end-start)));
            start = end + 1;
        }
    } 
    res.push_back((unsigned int)stoi(str.substr(start, str.size()-start)));
}

bool isCommonNet(vector<unsigned int>& mask, vector<unsigned int>& IP1, vector<unsigned int>& IP2){
    unsigned int maskDeci = 0;
    unsigned int IP1Deci = 0;
    unsigned int IP2Deci = 0;
    for(int i = 0; i < mask.size(); ++i){
        maskDeci += mask[i] * pow(2, 24-8*i); 
        IP1Deci += IP1[i] * pow(2, 24-8*i);
        IP2Deci += IP2[i] * pow(2, 24-8*i);
    }

    return (IP1Deci & maskDeci) == (IP2Deci & maskDeci);
}

int main(int argc, char* argv[]){
    string maskStr;
    getline(cin, maskStr);
    string ip1Str, ip2Str;
    getline(cin, ip1Str);
    getline(cin, ip2Str);

    vector<unsigned int> mask;
    processor(maskStr, mask);
    vector<unsigned int> IP1;
    processor(ip1Str, IP1);
    vector<unsigned int> IP2;
    processor(ip2Str, IP2);
  
    if(!isValidMask(mask) || !isValidIP(IP1) || !isValidIP(IP2)){
        cout << 1 << endl;
        return 0;
    }

    isCommonNet(mask, IP1, IP2) ? cout << 0 : cout << 2;
    cout << endl;

    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
11-28 17:48
中山大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务