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

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

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

使用正则匹配子网掩码合法性

import java.util.Arrays;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int[] mask = input(in.nextLine()), ip1 = input(in.nextLine()), ip2 = input(in.nextLine());
            if (check(mask) && check(ip1) && check(ip2) && checkMask(mask)) {
                System.out.println(same(ip1, ip2, mask) ? 0 : 2);
            } else {
                System.out.println(1);
            }
        }
    }

    private static int[] input(String path) {
        return Arrays.stream(path.split("\\.")).mapToInt(Integer::parseInt).toArray();
    }

    private static boolean check(int[] ip) {
        for (int part : ip) {
            if (0 > part || part >= 256) {
                return false;
            }
        }
        return true;
    }

    private static boolean checkMask(int[] mask) {
        String bin = "";
        for (int part : mask) {
            String b = Integer.toBinaryString(part);
            while (b.length() < 8) {
                b = "0" + b;
            }
            bin += b;
        }
        return bin.matches("1+0+");
    }

    private static boolean same(int[] ip1, int[] ip2, int[] mask) {
        for (int i = 0; i < mask.length; i++) {
            if ((ip1[i] & mask[i]) != (ip2[i] & mask[i])) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

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