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

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

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

#include <iostream>
using namespace std;

int main() {
    int mask[4] = {0};
    int ip1[4] = {0};
    int ip2[4] = {0};
    char delimiter;
    int flag = 0;

    cin >> mask[0] >> delimiter >> mask[1]
        >> delimiter >> mask[2] >> delimiter >> mask[3];
    cin >> ip1[0] >> delimiter >> ip1[1]
        >> delimiter >> ip1[2] >> delimiter >> ip1[3];
    cin >> ip2[0] >> delimiter >> ip2[1]
        >> delimiter >> ip2[2] >> delimiter >> ip2[3];

    for (int i = 0; i < 4 ; i++) {
        if (mask[i] < 0 || mask[i] > 255 || ip1[i] < 0 || ip1[i] > 255 || ip2[i] < 0 ||
                ip2[i] > 255) {
            flag = 1;
            break;
        }
    }

    for (int i = 0; i < 3 ; i++) {
        if (mask[i] < 255 && mask[i + 1] > 0) {
            flag = 1;
            break;
        }
    }
    if (flag == 1) {
        cout << flag << endl;
        return 0;
    }

    for (int i = 0; i < 4 ; i++) {
        // cout << mask[i] << endl;
        // cout << ip1[i] << endl;
        // cout << ip2[i] << endl;
        if ((ip1[i]&mask[i]) != (ip2[i]&mask[i])) {
            flag = 2;
            cout << flag << endl;
            return 0;
        }
    }
    flag = 0;
    cout << flag << endl;

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

全部评论

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务