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

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

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

import javax.imageio.metadata.IIOMetadataNode;
import javax.security.sasl.SaslClient;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String maskCode = sc.nextLine();
        String ip1 = sc.nextLine();
        String ip2 = sc.nextLine();
        if (isMaskCodeLawful(maskCode) && isIpLawful(ip1) && isIpLawful(ip2)) {
            System.out.println(isInSameInternet(maskCode, ip1, ip2));
        } else {
            System.out.println(1);
        }

    }

    private static int isInSameInternet(String maskCode, String ip1, String ip2) {
        String[] mask = maskCode.split("\\.");
        String[] nums1 = ip1.split("\\.");
        String[] nums2 = ip2.split("\\.");
        for (int i = 0; i < 4; i++) {
            if ((Integer.parseInt(mask[i]) & Integer.parseInt(nums1[i])) !=
                    (Integer.parseInt(mask[i]) & Integer.parseInt(nums2[i]))
            ) {
                return 2;
            }
        }
        return 0;
    }

    private static boolean isIpLawful(String ip) {
        String[] nums = ip.split("\\.");
        for (String num : nums) {
            if (Integer.parseInt(num) > 255 || Integer.parseInt(num) < 0) {
                return false;
            }
        }
        return true;
    }

    private static boolean isMaskCodeLawful(String maskCode) {
        if(!isIpLawful(maskCode)){
            return false;
        }
        String[] nums = maskCode.split("\\.");
        //最后一个1的位置  等于  所有1的数量
        String totalBinStr = "";
        for (String num : nums) {
            String binStr = Integer.toBinaryString(Integer.parseInt(num));
            while (binStr.length() < 8) {
                binStr = "0" + binStr;
            }
            totalBinStr += binStr;
        }
        int count = 0;
        for (char c : totalBinStr.toCharArray()) {
            if (c == '1') {
                count++;
            }
        }
        if ((count - 1) == totalBinStr.lastIndexOf("1")) {
            return true;
        }
        return false;
    }
}

全部评论

相关推荐

05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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