题解 | #识别有效的IP地址和掩码并进行分类统计#

识别有效的IP地址和掩码并进行分类统计

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

抄大佬的就完事了

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int illegal = 0;
        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        int e = 0;
        int pri = 0;
        while (in.hasNextLine()) {
            String s = in.nextLine();
            String[] split = s.split("~");
            String ip = split[0];
            String mask = split[1];
            String ipRegex = "^(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
            if (ip.matches(ipRegex)) {
                String[] ips = ip.split("\\.");
                int ip1 = Integer.parseInt(ips[0]);
                if (ip1 == 0 || ip1 == 127) {
                    continue;
                }
                String[] masks = mask.split("\\.");
                String maskStr = toBinary(masks[0]) + toBinary(masks[1]) + toBinary(masks[2]) + toBinary(masks[3]);
                if (!maskStr.matches("^1+0+$")) {
                    illegal++;
                    continue;
                }
                int ip2 = Integer.parseInt(ips[1]);
                if (ip1 >= 1 && ip1 <= 126) {
                    a++;
                } else if (ip1 >= 128 && ip1 <= 191) {
                    b++;
                } else if (ip1 >= 192 && ip1 <= 223) {
                    c++;
                } else if (ip1 >= 224 && ip1 <= 239) {
                    d++;
                } else if (ip1 >= 240 && ip1 <= 255) {
                    e++;
                }
                if (ip1 == 10 || (ip1 == 172 && ip2 >= 16 && ip2 <= 31) || (ip1 == 192 && ip2 == 168)) {
                    pri++;
                }
            } else {
                illegal++;
            }
        }
        System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + illegal + " " + pri);
    }

    public static String toBinary(String num) {
        StringBuilder numBinary = new StringBuilder(Integer.toBinaryString(Integer.parseInt(num)));
        while (numBinary.length() < 8) {
            numBinary.insert(0, "0");
        }
        return numBinary.toString();
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-13 14:16
战争学院:你妈妈第一反应是骗子,我妈妈第一反应是培训贷,全国家长系统是统一的吗哈哈哈
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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