小坑略多 怪我没有透彻领悟题意
import java.util.Scanner;
public class Main {
private static int A = 0;
private static int B = 0;
private static int C = 0;
private static int D = 0;
private static int E = 0;
private static int wrongIpOrMaskCount = 0;
private static int privateIpCount = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String s = in.nextLine();
solution(s);
}
System.out.printf("%d %d %d %d %d %d %d", A, B, C, D, E, wrongIpOrMaskCount,
privateIpCount);
}
public static void solution(String s) {
String[] ipAndMask = s.split("~");
String ip = ipAndMask[0];
String mask = ipAndMask[1];
boolean isLegalIp = isLegalIp(ip);
boolean isLegalMask = isLegalMask(mask);
if (isLegalIp) {
int[] vip = values(ip);
if (isLegalMask) {
int[] vm = values(mask);
stat(mask(vip, vm));
} else {
// 【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
if (vip[0] != 0 && vip[0] != 127) {
wrongIpOrMaskCount++;
}
}
} else {
wrongIpOrMaskCount++;
}
}
public static int[] mask(int[] v, int[] m) {
for (int i = 0; i < v.length; i++) {
v[i] &= m[i];
}
return v;
}
public static void stat(int[] v) {
// A 类地址从 1.0.0.0 到 126.255.255.255
if (1 <= v[0] && v[0] <= 126) {
A++;
}
// B 类地址从 128.0.0.0 到 191.255.255.255
if (128 <= v[0] && v[0] <= 191) {
B++;
}
// C 类地址从 192.0.0.0 到 223.255.255.255
if (192 <= v[0] && v[0] <= 223) {
C++;
}
// D 类地址从 224.0.0.0 到 239.255.255.255
if (224 <= v[0] && v[0] <= 239) {
D++;
}
// E 类地址从 240.0.0.0 到 255.255.255.255
if (240 <= v[0] && v[0] <= 255) {
E++;
}
// 私网IP范围是:[10.0.0.0, 10.255.255.255] [172.16.0.0, 172.31.255.255] [192.168.0.0, 192.168.255.255]
// 私有IP地址和 A,B,C,D,E 类地址是不冲突的
if (v[0] == 10
|| (v[0] == 172 && 16 <= v[1] && v[1] <= 31)
|| (v[0] == 192 && v[1] == 168)) {
privateIpCount++;
}
}
public static boolean isLegalMask(String mask) {
if (!isLegalIp(mask)) {
return false;
} else {
int[] v = values(mask);
int x = v[0] << 24 | v[1] << 16 | v[2] << 8 | v[3];
// 二进制下全是0或者全是1均为非法子网掩码
if (x == 0 || x == -1) {
return false;
}
boolean hasSeenZero = false;
while (x != 0) {
// 最高位为1 则这个数为负数
if (x < 0) {
// 一旦看到0,就不应该有1
if (hasSeenZero) {
return false;
}
} else {
hasSeenZero = true;
}
x <<= 1;
}
return true;
}
}
public static int[] values(String ip) {
String[] strs = ip.split("\\.");
int[] v = new int[strs.length];
for (int i = 0; i < v.length; i++) {
v[i] = Integer.parseInt(strs[i]);
}
return v;
}
public static boolean isLegalIp(String s) {
String[] ip = s.split("\\.");
if (ip.length != 4) {
return false;
}
int legalCount = 0;
for (int i = 0; i < ip.length; i++) {
// ip的合法范围是 [0, 255]
if (ip[i].matches("[1-9]\\d*|0") && Integer.parseInt(ip[i]) <= 255) {
legalCount++;
}
}
return legalCount == 4;
}
}

京公网安备 11010502036488号