题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
!!个人解法,非最优!!
我真服了这题,面相答案编程。。
- 先判断IP 中 0 与 127 开头
- 检查掩码(因为掩码有一票否决权)
- 检查IP 和 私有IP
import java.util.Scanner;
import java.util.*;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static final int[] ans = new int[7];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
next:
while (in.hasNext()) { // 注意 while 处理多个 case
String[] strs = in.nextLine().split("~");
String[] addr = strs[0].split("\\.");
String[] mask = strs[1].split("\\.");
// check 0 and 127
int p0 = addr[0] != null ? Integer.parseInt(addr[0]) : 0;
if (p0 == 0 || p0 == 127) {
continue;
}
// check Mask
if (isIllegalMask(mask)) {
ans[5]++;
continue;
} else {
int pre = 0;
for (int i = mask.length - 1; i >= 0; i--) {
int part = Integer.parseInt(mask[i]);
int x = 255;
while (x != 0) {
int cur = 0;
if ((cur = (part & 1)) < pre) {
ans[5]++;
continue next;
}
pre = cur;
part >>= 1;
x >>= 1;
}
}
}
// check IP and Private IP
if (isIllegalIP(addr)) {
ans[5]++;
} else if (p0 >= 1 && p0 <= 126) {
// A class
ans[0]++;
if (p0 == 10) ans[6]++;
} else if (p0 >= 128 && p0 <= 191) {
// B class
ans[1]++;
int p1 = Integer.parseInt(addr[1]);
if (p0 == 172 && p1 >= 16 && p1 <= 31) ans[6]++;
} else if (p0 >= 192 && p0 <= 223) {
// C class
ans[2]++;
int p1 = Integer.parseInt(addr[1]);
if (p0 == 192 && p1 == 168) ans[6]++;
} else if (p0 >= 224 && p0 <= 239) {
// D class
ans[3]++;
} else if (p0 >= 240 && p0 <= 255) {
// E class
ans[4]++;
} else {
ans[5]++;
}
}
System.out.println(String.join(" ",
Arrays.stream(ans).mapToObj(String::valueOf).toArray(String[]::new)));
}
private static boolean isIllegalIP(String[] addr) {
if (addr.length < 4) return true;
for (String i : addr) {
if ("".equals(i)) {
return true;
}
}
return false;
}
private static boolean isIllegalMask(String[] addr) {
if (addr.length < 4) return true;
boolean allZero = true;
boolean allOne = true;
for (String i : addr) {
if ("".equals(i)) {
return true;
}
allZero &= i.equals("0");
allOne &= i.equals("255");
}
return allZero || allOne;
}
}

查看4道真题和解析