题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
题目链接
识别有效的IP地址和掩码并进行分类统计本题基本考察的就是字符串的比较与判断,其中需要注意对子网掩码的判断
思路分析
1. 首先 按行读取信息 分割字符 "~" 得到 IP地址以及子网掩码地址;
2. 其次 若IP地址是0或者127开头的直接跳过;
3. 然后 对所分割的地址进行比较分析 即需要从以下三步分析:
- 由于错误的IP地址及错误的掩码属于一类 故先判断掩码是否错误,若错误直接增加错误地址数;
- 判断IP地址是否合法若不合法 即直接增加错误地址数;
-
最后判断IP地址属于哪类。
具体实现
下面代码有详细注释 :)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static String toBinary(String num) {
String numBinary = Integer.toBinaryString(Integer.valueOf(num));
// 如果数字过小转换的二进制不足8位 则需要在前面补0
while (numBinary.length() < 8) {
numBinary = "0" + numBinary;
}
return numBinary;
}
// 如果子网掩码异常 return true
private static boolean isMaskValid(String[] mask){
if (mask.length != 4) {
return true;
}
String maskBinary = toBinary(mask[0]) + toBinary(mask[1]) + toBinary(mask[2]) + toBinary(mask[3]);
// maskBinary 应该是一个有n个1和m个0组成的字符串 即 11111..1000..0
if (!maskBinary.matches("[1]{1,}[0]{1,}")) {
return true;
}
return false;
}
// 判断IP是否合法 例如出现不全如 19..0. 如果不合法返回true
private static boolean isIpValid(String[] ip){
if(ip.length!=4) return true;
for(String s : ip){
if(s.equals("")) return true;
if(Integer.parseInt(s)>255) return true;
}
return false;
}
// Ip a.b.c.d
private static Character isIp(String[] ip){
int a = Integer.parseInt(ip[0]);
int b = Integer.parseInt(ip[1]);
int c = Integer.parseInt(ip[2]);
int d = Integer.parseInt(ip[3]);
if(a>=1 && a<=126) return 'A';
else if(a>=128 && a<=191) return 'B';
else if(a>=192 && a<=223) return 'C';
else if(a>=224 && a<=239) return 'D';
else if(a>=240 && a<=255) return 'E';
else return 'W';
}
private static boolean isPrivateIP(String[] ip){
int a = Integer.parseInt(ip[0]);
int b = Integer.parseInt(ip[1]);
int c = Integer.parseInt(ip[2]);
int d = Integer.parseInt(ip[3]);
if(a==10 || (a==172 && (b>=16 && b<=31)) || (a==192 && b==168)) return true;
else return false;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
// 对应ABCDE IP地址 错误 及私有
int a = 0, b=0, c=0, d=0, e=0, wrong=0, p=0;
while((s=br.readLine())!=null){
// 分割IP地址和掩码
String[] ss = s.split("\\~");
// 分割ip地址和掩码
String[] ip = ss[0].split("\\.");
String[] mask = ss[1].split("\\.");
// 开头是 0/127的IP地址忽略
if(ip[0].equals("0") || ip[0].equals("127")) continue;
// 先判断掩码有无问题
if(isMaskValid(mask)){
wrong++;
continue;
}
// 再判断IP地址有无问题
if(isIpValid(ip)){
wrong++;
continue;
}
// 判断IP地址属于哪类
if(isIp(ip)=='A') a++;
else if(isIp(ip)=='B') b++;
else if(isIp(ip)=='C') c++;
else if(isIp(ip)=='D') d++;
else if(isIp(ip)=='E') e++;
else wrong++;
// 判断是不是private IP
if(isPrivateIP(ip)) p++;
}
System.out.print(a+" "+b+" "+c+" "+d+" "+e+" "+wrong+" "+p);
}
}
