题解 | 识别有效的IP地址和掩码并进行分类统计
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int pri = 0;
int error = 0;
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
String[] IPs = str.split("~");
boolean isE = true;
//判断IP是否合法
String[] IP = IPs[0].split("\\.");
if (IP[0].equals("0") || IP[0].equals("127")) {
continue;
}
for (int i = 0; i <= 3; i++) { //判断是否有空
if (IP[i].equals("")) {
isE = false;
break;
}
}
if (!isE) {
error++;
continue;
}
//子网掩码是否合法
String[] ips = IPs[1].split("\\.");
for (int i = 0; i <= 3; i++) { //判断是否有空
if (ips[i].equals("")) {
isE = false;
break;
}
}
if (!isE) {
error++;
continue;
}
int[] part = new int[4]; //存放十进制
String ziW = new String(); //存放二进制子网掩码
for (int i = 0; i <=3; i++) { //进制转换
part[i] = Integer.parseInt(ips[i]);
ips[i] = String.format("%8s",Integer.toBinaryString(part[i])).replace(' ', '0'); //转换成二进制
ziW = ziW + ips[i];
}
int index0 = ziW.indexOf('0');
int index1 = ziW.indexOf('1');
if (index0 == -1 || index1 == -1) {
error++;
continue;
}
String ziWChange = ziW.substring(index0);
if (ziWChange.indexOf('1') >= 0) {
error++;
continue;
}
//判断IP是哪一类
int ten = Integer.parseInt(IP[0]);
int ten2 = Integer.parseInt(IP[1]);
if (ten >= 1 && ten <= 127) {
a++;
} else if (ten >= 128 && ten <= 191) {
b++;
} else if (ten >= 192 && ten <= 223) {
c++;
} else if (ten >= 224 && ten <= 239) {
d++;
} else {
e++;
}
if (ten == 10) {
pri++;
} else if (ten == 172 && ten2 >= 16 && ten2 <= 31) {
pri++;
} else if (ten == 192 && ten2 == 168) {
pri++;
}
}
System.out.print(a + " " + b +" "+c+" "+d+" "+e+" "+error+" "+pri);
}
}
