题解 | #判断两个IP是否属于同一子网#拆分为几个小问题

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

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        label:
        while (in.hasNextLine()) {
            String subnetMask = in.nextLine();
            String ip1 = in.nextLine();
            String ip2 = in.nextLine();

            if (isLegal(subnetMask) && ipIsLegal(ip1) && ipIsLegal(ip2)) {
                String[] split = subnetMask.split("\\.");
                String[] split1 = ip1.split("\\.");
                String[] split2 = ip2.split("\\.");
                for (int i = 0; i < 4; i++) {
                    int m = Integer.parseInt(split[i]);
                    int i1 = Integer.parseInt(split1[i]);
                    int i2 = Integer.parseInt(split2[i]);
                    if (((m & i1) ^ (m & i2)) != 0) {
                        System.out.println(2);
                        continue label;
                    }
                }
                System.out.println(0);

            } else {
                System.out.println(1);
            }
        }
    }

    private static boolean ipIsLegal(String ip) {
        String[] split = ip.split("\\.");
        if (split.length != 4) return false;
        for (int i = 0; i < split.length; i++) {
            int sub = Integer.parseInt(split[i]);
            if (sub > 255 || sub < 0) return false;
        }
        return true;
    }

    private static boolean isLegal(String str) {
        String[] split = str.split("\\.");
        String subNetMask = Arrays.stream(split).map(Long::parseLong).map(Long::toBinaryString)
                .map(s -> {
                    if (s.length() < 8)
                        s = "00000000".substring(s.length()) + s;
                    return s;
                }).reduce(String::concat).get();

        return subNetMask.length() == 32 && subNetMask.matches("1+0+") ;
    }
}

全部评论

相关推荐

Z_eus:别打招呼直接发你的优势
点赞 评论 收藏
分享
喜欢疯狂星期四的猫头鹰在研究求职打法:短作业优先
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务