题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
我是真的无力吐槽这种题目,讲的不清不楚的!!!!!
注意点:
-1 255.255.255.255 不算子网掩码(调试1小时才发现)
-2 题目说的是,错误IP地址或错误掩码,就是这条输入错误了意思,
-3 说句实话,做这种写的又臭又长看的都恶心的代码不如不写
import java.security.PublicKey; import java.util.*; /*输入: 10.70.44.68~255.254.255.0 1.0.0.1~255.0.0.0 192.168.0.2~255.255.255.0 19..0.~255.255.255.0 复制 输出: 1 0 1 0 0 2 1 */ public class Main { static int A = 0, B = 0, C = 0, D = 0, E = 0, error = 0, pri = 0; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String s = scanner.nextLine(); String[] split = s.split("~"); if (split.length != 2) { error++; continue; } String left = split[0]; String right = split[1]; help(left, right); // System.out.println(A + " " + B + " " + C + " " + D + " " + E + " " + error + " " + pri); } System.out.println(A + " " + B + " " + C + " " + D + " " + E + " " + error + " " + pri); } private static void help(String left, String right) { String[] ips = left.split("\\."); String[] ip_2s = right.split("\\."); if (ips.length != 4 || ip_2s.length != 4) { error++; return; } int ip0 = Integer.parseInt(ips[0]); int ip1 = Integer.parseInt(ips[1]); int ip2 = Integer.parseInt(ips[2]); int ip3 = Integer.parseInt(ips[3]); int ip_0 = Integer.parseInt(ip_2s[0]); int ip_1 = Integer.parseInt(ip_2s[1]); int ip_2 = Integer.parseInt(ip_2s[2]); int ip_3 = Integer.parseInt(ip_2s[3]); if (ip0 > 255 || ip1 > 255 || ip2 > 255 || ip3 > 255 || ip_0 > 255 || ip_1 > 255 || ip_2 > 255 || ip_3 > 255) { error++; return; } if (!judge(ip_0, ip_1, ip_2, ip_3)) { error++; return; } if (ip0 > 0 && ip0 < 127) { A++; if (ip0 == 10) { pri++; } return; } else if (ip0 > 127 && ip0 < 192) { B++; if (ip0 == 172 && ip1 >= 16 && ip1 <= 31) { pri++; } return; } else if (ip0 >= 192 && ip0 <= 223) { C++; if (ip0 == 192 && ip1 == 168) { pri++; } } else if (ip0 >= 224 && ip0 <= 239) { D++; } else if (ip0 >= 240 && ip0 <= 255) { E++; } } private static boolean judge(int ip_0, int ip_1, int ip_2, int ip_3) { if (ip_0 == 255 && ip_1 == 255 && ip_2 == 255 && ip_3 == 255) { return false; } String i_0 = Integer.toBinaryString(ip_0); String i_1 = Integer.toBinaryString(ip_1); String i_2 = Integer.toBinaryString(ip_2); String i_3 = Integer.toBinaryString(ip_3); while (i_1.length() < 8) { i_1 = "0" + i_1; } while (i_2.length() < 8) { i_2 = "0" + i_2; } while (i_3.length() < 8) { i_3 = "0" + i_3; } char[] chars = (i_0 + i_1 + i_2 + i_3).toCharArray(); boolean flage = false; for (int i = 0; i < chars.length; i++) { if (chars[i] == '0') { flage = true; } if (flage == true && chars[i] == '1') { return false; } } return true; } }