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

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

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

#include <iostream>
#include <sstream>
#include <string>
#include <bitset>
using namespace std;

bool is_ip(const string& ip) {
    stringstream ss(ip);
    string token;
    while (getline(ss, token, '.')) {
        int n = stoi(token);
        if (n > 255 || n < 0) {
            return false;
        }
    }
    return true;
}

string get_binary_str(const string& ip) {
    string binary_str;
    stringstream ss(ip);
    string token;
    while (getline(ss, token, '.')) {
        bitset<8> b(stoi(token));
        binary_str += b.to_string();
    }
    return binary_str;
}

bool is_mask(const string& mask) {
    if (!is_ip(mask)) return false;

    string binary_str = get_binary_str(mask);
    bool seen_zero = false;
    for (const char& c : binary_str) {
        if (c == '0') {
            seen_zero = true;
        }
        if (c == '1' && seen_zero) {
            return false;
        }
    }
    return true;
}

int main() {
    string ip1, ip2, mask;
    while (cin >> mask >> ip1 >> ip2) {
        if (!is_ip(ip1) || !is_ip(ip2) || !is_mask(mask)) {
            cout << 1 << endl;
            continue;
        }

        string ip1_str = get_binary_str(ip1);
        string ip2_str = get_binary_str(ip2);
        string mask_str = get_binary_str(mask);
        for (int i = 0; i < 32; ++i) {
            if (mask_str[i] == '0') {
                ip1_str[i] = '0';
                ip2_str[i] = '0';
            }
        }
        cout << (ip1_str == ip2_str ? 0 : 2) << endl;
    }


    return 0;
}

全部评论

相关推荐

10-15 20:01
已编辑
上海大学 Java
钉钉什么垃圾公司,约面鸽人
光年在眼前:不是坏事,感觉钉钉挺逆天的,二面结束还给我留作业,让我使用钉钉和看最新的发布会,然后说感受,我是应该不会去,三面直接拒绝不面了
点赞 评论 收藏
分享
09-19 13:59
门头沟学院 Java
用微笑面对困难:Trae一下,如果真成了,他用了直接发字节起诉代码版权,,这个代码不商用是没问题的如果没成也是情理之中的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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