题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import java.util.*; public class Main { public static void main(String[] args) { Scanner fzhinput = new Scanner(System.in); int a = 0, b = 0, c = 0, d = 0, e = 0, ff = 0, pnum = 0; while (fzhinput.hasNextLine()) { String srdz = fzhinput.nextLine(); String dz[] = srdz.split("~"); if (dz.length != 2) { ff++; continue; } String ipdz[] = dz[0].split("\\."); String zwym[] = dz[1].split("\\."); int sz, sz1; sz = Integer.parseInt(ipdz[0]); if (!isValIP(ipdz) || !isValYM(zwym)) { if (sz == 127 || sz == 0) { } else { ff++; continue; } } if (sz >= 1 && sz <= 126) { a++; } else if (sz >= 128 && sz <= 191) { b++; } else if (sz >= 192 && sz <= 223) { c++; } else if (sz >= 224 && sz <= 239) { d++; } else if (sz >= 240 && sz <= 255) { e++; } sz1 = Integer.parseInt(ipdz[1]); if (sz == 10) { pnum++; } else if (sz == 172 && sz1 <= 31 && sz1 >= 16 ) { pnum++; } else if (sz == 192 && sz1 == 168) { pnum++; } } System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+ff+" "+pnum); } public static boolean isValIP(String[] ipdz) { boolean result = true; if (ipdz.length != 4) { result = false; } else { for (int i = 0; i < ipdz.length; i++) { int num = Integer.parseInt(ipdz[i]); if (num > 255 || num < 0) { result = false; } } } return result; } public static boolean isValYM(String[] zwym) { boolean result = true; StringBuilder stack = new StringBuilder(); if (zwym.length != 4) { result = false; } else { for (int i = 0; i < zwym.length; i++) { int num = Integer.parseInt(zwym[i]); String erjz = String.format("%8s",Integer.toBinaryString(num)).replace(" ","0"); stack.append(erjz); if (num > 255 || num < 0) { result = false; } } String nerjz = stack.toString(); if(nerjz.equals("00000000000000000000000000000000")||nerjz.equals("11111111111111111111111111111111")){ result = false; } else if(nerjz.matches("^1+0*$")){ result = true; } else{ result = false; } } return result; } }