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

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

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

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.hasNext()) { // 注意 while 处理多个 case
            String ym = in.nextLine();
            String ip1 = in.nextLine();
            String ip2 = in.nextLine();

            if (!(ipTest(ip1) && ipTest(ip2) && ymTest(ym))) {
                System.out.println("1");
                continue;
            }

            String m = invert(ip1, ym);
            String n = invert(ip2, ym);
            if (!m.equals(n)) {
                System.out.println("2");
            } else {
                System.out.println("0");
            }

        }
    }

    public static String invert(String ip, String ym) {
        String[] ips = ip.split("\\.");
        String[] yms = ym.split("\\.");
        StringBuilder sum = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int a = Integer.parseInt(ips[i]);
            int b = Integer.parseInt(yms[i]);
            int c = a & b;
            sum.append(c);
            if (i != 3) {
                sum.append(".");
            }
        }
        return sum.toString();
    }

    public static boolean ipTest(String ip) {
        String[] ips = ip.split("\\.");
        for (int i = 0; i < ips.length; i++) {
            int a = Integer.parseInt(ips[i]);
            if (a < 0 || a > 255) {
                return false;
            }
        }
        return true;
    }

    public static boolean ymTest(String ym) {
        String[] yms = ym.split("\\.");
        StringBuilder sum = new StringBuilder();
        for (int i = 0; i < yms.length; i++) {
            int a = Integer.parseInt(yms[i]);
            if (a < 0 || a > 255) {
                return false;
            }
            String s = Integer.toBinaryString(a);
            while (s.length() < 8) {
                s = "0" + s;
            }
            sum.append(s);
        }
        if (!sum.toString().matches("[1]{1,}[0]{1,}")) {
            return false;
        }
        return true;
    }
}

全部评论

相关推荐

自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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