题解 | #识别有效的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);
String input;
int countA = 0;
int countB = 0;
int countC = 0;
int countD = 0;
int countE = 0;
int errorIPOrErrorMask = 0;
int privateIP = 0;
String ip;
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
input = in.nextLine();
String[] str = input.split("~");
if(isValidIp(str[0]) && isMask(str[1])){
if(Integer.parseInt(str[0].split("\\.")[0]) >= 1 && Integer.parseInt(str[0].split("\\.")[0]) <= 126){
countA++;
if(Integer.parseInt(str[0].split("\\.")[0]) == 10){
privateIP++;
}
}
if(Integer.parseInt(str[0].split("\\.")[0]) >= 128 && Integer.parseInt(str[0].split("\\.")[0]) <= 191){
countB++;
if(Integer.parseInt(str[0].split("\\.")[0]) == 172 && Integer.parseInt(str[0].split("\\.")[1]) >= 16 && Integer.parseInt(str[0].split("\\.")[1]) <= 31){
privateIP++;
}
}
if(Integer.parseInt(str[0].split("\\.")[0]) >= 192 && Integer.parseInt(str[0].split("\\.")[0]) <= 223){
countC++;
if(Integer.parseInt(str[0].split("\\.")[0]) == 192 && Integer.parseInt(str[0].split("\\.")[1]) == 168){
privateIP++;
}
}
if(Integer.parseInt(str[0].split("\\.")[0]) >= 224 && Integer.parseInt(str[0].split("\\.")[0]) <= 239){
countD++;
}
if(Integer.parseInt(str[0].split("\\.")[0]) >= 240 && Integer.parseInt(str[0].split("\\.")[0]) <= 255){
countE++;
}
}else{
if(str[1].equals("0.0.0.0") || str[1].equals("255.255.255.255") || (Integer.parseInt(str[0].split("\\.")[0])!= 127 && Integer.parseInt(str[0].split("\\.")[0]) != 0))
errorIPOrErrorMask++;
}
}
System.out.print(countA + " " + countB + " " + countC + " " + countD + " " + countE + " " + errorIPOrErrorMask + " " + privateIP);
}
public static boolean isMask(String string){
String[] str = string.split("\\.");
StringBuilder strBuild = new StringBuilder();
if(str.length != 4){
return false;
}else{
for(int i = 0; i < str.length; i++){
String temp = Integer.toBinaryString(Integer.parseInt(str[i]));
if(temp.length() < 8){
for(int j = 0; j < 8 - temp.length(); j++){
strBuild.append("0");
}
strBuild.append(temp);
}else{
strBuild.append(temp);
}
}
if(strBuild.toString().equals("0000000000000000") || strBuild.toString().equals("1111111111111111")){
return false;
}
}
return strBuild.toString().indexOf("0") > strBuild.toString().lastIndexOf("1");
}
public static boolean isValidIp(String string){
String[] str = string.split("\\.");
if(str.length != 4){
return false;
}else{
if(Integer.parseInt(str[0]) == 0 || Integer.parseInt(str[0]) == 127){
return false;
}
if(!(Integer.parseInt(str[1]) >= 0 && Integer.parseInt(str[1]) <= 255 && Integer.parseInt(str[2]) >= 0 && Integer.parseInt(str[2]) <= 255 && Integer.parseInt(str[3]) >= 0 && Integer.parseInt(str[3]) <= 255)){
return false;
}
}
return true;
}
}