题解 | #判断两个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;
    }
}

全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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