题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
public class Main
{
static final String FORMAT_STRING = "00000000";
public static String addString(String src)
{
if (null == src) {
return null;
}
int delta = FORMAT_STRING.length() - src.length();
if (delta <= 0) {
return src;
}
return FORMAT_STRING.substring(0, delta) + src;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int numberA=0,numberB=0,numberC=0,numberD=0,numberE=0;
int mistakeIP=0,mistakeMask=0;
int privateIP=0;
String handleIP,handleMask;
while(sc.hasNext())
{
String input=sc.nextLine();
handleIP=input.substring(0,input.indexOf("~"));
handleMask=input.substring(input.indexOf("~")+1);
String[] cutIP = handleIP.split("\\.");
String[] cutMask = handleMask.split("\\.");
String cutOne = Integer.toBinaryString( Integer.parseInt(cutMask[0]));
String cuttwo = Integer.toBinaryString( Integer.parseInt(cutMask[1]));
String cutthree = Integer.toBinaryString( Integer.parseInt(cutMask[2]));
String cutfour = Integer.toBinaryString( Integer.parseInt(cutMask[3]));
String together = addString(cutOne)+addString(cuttwo)+addString(cutthree)+addString(cutfour);
if((together.indexOf("0")<=together.lastIndexOf("1"))
&&Integer.parseInt(cutIP[0])!=0
&&Integer.parseInt(cutIP[0])!=127)
{
mistakeMask++;
cutIP[0]="-1";
}
for(int i=0;i<cutIP.length;i++)
{
if(cutIP[i].equals(""))
cutIP[0]="-1";
}
if((Integer.parseInt(cutIP[0])<127)&&(Integer.parseInt(cutIP[0])>0))
{
if(Integer.parseInt(cutIP[0])==10)
privateIP++;
numberA++;
}
else if(Integer.parseInt(cutIP[0])<192&&Integer.parseInt(cutIP[0])>127)
{
if(Integer.parseInt(cutIP[0])==172
&&Integer.parseInt(cutIP[1])>=16
&&Integer.parseInt(cutIP[1])<=31)
privateIP++;
numberB++;
}
else if(Integer.parseInt(cutIP[0])<224&&Integer.parseInt(cutIP[0])>191)
{
if(Integer.parseInt(cutIP[0])==192
&&Integer.parseInt(cutIP[1])==168)
privateIP++;
numberC++;
}
else if(Integer.parseInt(cutIP[0])<240&&Integer.parseInt(cutIP[0])>223)
numberD++;
else if(Integer.parseInt(cutIP[0])<256&&Integer.parseInt(cutIP[0])>239)
numberE++;
else if(Integer.parseInt(cutIP[0])==0||Integer.parseInt(cutIP[0])==127)
continue;
else
{
mistakeIP++;
}
}
int abc = mistakeMask+mistakeIP;
System.out.print(numberA+" "+numberB+" "+numberC+" "+numberD
+" "+numberE+" "+mistakeIP+" "+privateIP);
}
}