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

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

static regex netReg(
    R"(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))");
bool isVaildIp(const string& ip) {
    return regex_match(ip, netReg);
}

bool isVaildMask(const string& mask) {
    if (!regex_match(mask, netReg)) return false;

    stringstream ss(mask);
    string segment;
    unsigned long binaryMask = 0;
    while (getline(ss, segment, '.')) {
        binaryMask = (binaryMask << 8) | stoi(segment);
    }
    //cout << binary << endl;

    bitset<32> b(binaryMask);
    bool found = false;
    for (int i = 31; i >= 0; --i) {
        if (!b.test(i)) {
            found = true;
        } else if (found) {
            return false;
        }
    }
    return !(binaryMask == 0 || binaryMask == 0xFFFFFFFF);;

}
bitset<32> andOperate(const string ip, const string mask) {
    stringstream ss(mask);
    string segment;
    unsigned long binaryMask = 0;
    while (getline(ss, segment, '.')) {
        binaryMask = (binaryMask << 8) | stoi(segment);
    }
    bitset<32> bmask(binaryMask);

    stringstream ss2(ip);
    string segment2;
    unsigned long binaryIp = 0;
    while (getline(ss2, segment2, '.')) {
        binaryIp = (binaryIp << 8) | stoi(segment2);
    }
    bitset<32> bip(binaryIp);

    return  bip & bmask;

}
int main() {
    string  mask, ip1, ip2;
    while (cin >> mask >> ip1 >> ip2) { // 注意 while 处理多个 case
        if (isVaildMask(mask) && isVaildIp(ip1) && isVaildIp(ip2)) {
            cout << (andOperate(ip1, mask) == andOperate(ip2, mask) ? 0 : 2) << endl;
        } else {
            cout << 1 << endl;
        }

    }
}

全部评论

相关推荐

06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
07-11 22:27
中南大学 Java
程序员牛肉:学历的话没问题。但是没问题的也就只有学历了。 其实你的整体架构是正确的,博客接着干。但是项目有点过于简单了。从后端的角度上讲,你这也就是刚入门的水平,所以肯定约面试够呛。 如果你要应聘后端岗位,那你第一个项目竟然是仿写操作系统。这个你要面试官咋问你。你一定要记住一点,你简历上写的所有的东西,都是为了证明你有能力胜任当前的岗位,而不是为了证明你自己会什么。 如果你只是浅浅的做几个项目,描述也都是烂大街。技术点也都是各种混水类的配置类需求,那你就不要幻想自己能走多远。一定要保持思考,保持学习。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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