题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
花了两个半小时,就一直调试
import java.io.*;
public class Main{
//public static
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Scanner sc=new Scanner(System.in);
int counts[]=new int[7];
String s=null;
while((s=br.readLine())!=null){
//s=sc.next();
String[] str1=s.split("~");
String[] str2=str1[0].split("\\.");
//String[] str3=str1[1].split("\\.");
char chars[][]=new char[4][8];
if(isYanma(str1[1])==false&&
Integer.parseInt(str2[0])!=0&&Integer.parseInt(str2[0])!=127) {
counts[5]=counts[5]+1;
continue;
}
if(isValidIp(counts,str1[0])==false) {
counts[5]=counts[5]+1;
continue;
}
}
for(int i=0;i<counts.length;i++){
System.out.print(counts[i]+" ");
}
}
public static boolean isValidIp(int[] counts,String s){
String[] str=s.split("\\.");
if(Integer.parseInt(str[0])==0||Integer.parseInt(str[0])==127) return true;
for(int i=0;i<str.length;i++){
if("".equals(str[i])) {
//System.out.println(str[i]);
return false;
}
int val=Integer.parseInt(str[i]);
if(val<0&&val>255) return false;
}
int val=Integer.parseInt(str[0]);
if(val==10){
counts[6]++;
counts[0]++;
}else if(val==192&&Integer.parseInt(str[1])==168){
counts[6]++;
counts[2]++;
}
else if(val==172&&Integer.parseInt(str[1])>=16
&&Integer.parseInt(str[1])<=31) {
counts[6]++;
}
else if(val>=1&&val<=126) counts[0]++;
else if(val>=128&&val<=191) counts[1]++;
else if(val>=192&&val<=223) counts[2]++;
else if(val>=224&&val<=239) counts[3]++;
else if(val>=240&&val<=255) counts[4]++;
else return false;
return true;
}
public static boolean isYanma(String s){
String str[]=s.split("\\.");
int flag=0;
int count11=0;
for(int i=0;i<str.length;i++){
int count=0;
int val=Integer.parseInt(str[i]);
if(flag==1 && (val&128)==128) return false;
while((val&128)==128){
count++;
count11++;
val=val<<1;
//System.out.println(count+" "+val);
}
if(((val&128)!=128)&&count<8) flag=1;
for(int j=0;j<8-count;j++){
if((val&128)==128&&flag==1){
return false;
}
val=val<<1;
}
}
if(count11==32||count11==0) return false;
return true;
}
}