题解 | #判断两个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.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        for (int i = 0; i < 3; i++) {
            if (!in.hasNextLine()) {
                break;
            }
            String code = in.nextLine();
            String ip1 = in.nextLine();
            String ip2 = in.nextLine();
            int result = -1;
            boolean isCode = isCode(code);
            boolean isIp1 = isIp(ip1);
            boolean isIp2 = isIp(ip2);
            if (!isCode || !isIp1 || !isIp2) {
                result = 1;
            } else {
                String codeBinary = toBinary(code);
                String ip1Binary = toBinary(ip1);
                String ip2Binary = toBinary(ip2);

                long codeLong = Long.parseLong(codeBinary, 2);
                long ip1Long = Long.parseLong(ip1Binary, 2);
                long ip2Long = Long.parseLong(ip2Binary, 2);
                long andIp1 = codeLong & ip1Long;
                long andIp2 = codeLong & ip2Long;
                if (andIp1 == andIp2) {
                    result = 0;
                } else {
                    result = 2;
                }
            }
            System.out.println(result);
        }

    }

    private static String toBinary(String ipOrCode) {
        String[] strs = ipOrCode.split("\\.");
        String binary = "";
        for (int i = 0; i < strs.length; i++) {
            int num = Integer.parseInt(strs[i]);
            if (num >= 0 && num <= 255) {
                String str = Integer.toBinaryString(num);
                int len = str.length();
                for (int j = 0; j < 8 - len; j++) {
                    str = "0" + str;
                }
                binary += str;
            } else {
                return null;
            }
        }
        return binary;
    }

    private static boolean isCode(String code) {
        String binary = toBinary(code);
        if (binary == null) {
            return false;
        }
        if (binary.contains("01")) {
            return false;
        } else {
            return true;
        }

    }

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

全部评论

相关推荐

wuwuwuoow:Redisson 写错了,记得 Redis 儿子以后都不会写错。其他没啥问题,海投就行。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务