题解 | #判断两个IP是否属于同一子网,易懂版?#

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

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

#include <iostream>
#include <bits/stdc++.h>
#include <sstream>
using namespace std;

bool judge_ip(string ip){
    istringstream s(ip);
    string temp;
    int j = 0;
    while(getline(s, temp, '.')){
        if(temp.empty() || stoi(temp) > 255 || j >= 4 || stoi(temp) < 0) //ip不空,0-255间,为4位
        {
            return false;
        }
        j++;
    }
    return j == 4; // ip 得是4位的
}
bool judge_mask(string mask){ //转化为二进制字符串,正则表达式匹配
    istringstream s(mask);
    string temp;
    regex pattern("[1]+[0]+");
    string string_mask = "";
    while(getline(s, temp, '.')){
        if(temp.empty() || stoi(temp) > 255 || stoi(temp) < 0){
            return false;
        }
        bitset<8> bit(stoi(temp));
        string_mask += bit.to_string();
    }
    
    if(regex_match(string_mask, pattern)){
        return true;
    }
    else{
        return false;
    }
}
bool same_net(string ip1, string ip2, string mask){//判断是否在同一子网
    string temp1, temp2, tempmask;
    istringstream s1(ip1), s2(ip2), s3(mask);
    for(int i = 0; i < 4; ++i){
        getline(s1, temp1, '.');
        getline(s2, temp2, '.');
        getline(s3, tempmask, '.');
        int tip1 = stoi(temp1);
        int tip2 = stoi(temp2);
        int tip3 = stoi(tempmask);
        if((tip1 & tip3)!=(tip2 & tip3)){
            return false;
        }
    }
    return true;

}

int main() {
    string mask;
    cin >> mask;
    string ip1, ip2;
    cin >> ip1;
    cin >> ip2;
    if(judge_mask(mask) == false || judge_ip(ip1) == false || judge_ip(ip2) == false){
        cout << 1 << endl;
        return 0;
    }
    if(same_net(ip1, ip2, mask)){
        cout << 0 << endl;
    }
    else{
        cout << 2 << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务