题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String mask = sc.nextLine();
String ip_a = sc.nextLine();
String ip_b = sc.nextLine();
// Check if the mask is illegal
if(judgeMask(mask) == 1) {
// Check ip address is illegal
if(judgeIpAddr(ip_a) == 1 && judgeIpAddr(ip_b) == 1) {
// Convert to long date type and compare those ips
Long maskq = ipConvertLong(mask);
Long ipA = ipConvertLong(ip_a)&maskq;
Long ipB = ipConvertLong(ip_b)&maskq;
if(ipA.equals(ipB)) {
System.out.println(0);
} else {
System.out.println(2);
}
} else {
System.out.println(1);
}
} else {
System.out.println(1);
}
}
}
private static int judgeMask(String s) {
String[] ss = s.split("\\.");
if(ss.length != 4) {
return 0;
}
for(String str: ss) {
if(Integer.parseInt(str) > 255 || Integer.parseInt(str) < 0) {
return 0;
}
}
for(int i = 0; i < 3; i++) {
if(Integer.parseInt(ss[i]) > 255 || Integer.parseInt(ss[i]) < 0) {
return 0;
}
if( i == 0 && Integer.parseInt(ss[i]) < 255) {
if(Integer.parseInt(ss[i+1]) > 0) {
return 0;
} else if(Integer.parseInt(ss[i+2]) > 0) {
return 0;
} else if(Integer.parseInt(ss[i+3]) > 0) {
return 0;
}
} else if( i == 1 && Integer.parseInt(ss[i]) < 255) {
if(Integer.parseInt(ss[i+1]) > 0) {
return 0;
} else if(Integer.parseInt(ss[i+2]) > 0) {
return 0;
}
} else if( i == 2 && Integer.parseInt(ss[i]) < 255) {
if(Integer.parseInt(ss[i+1]) > 0) {
return 0;
}
}
}
return 1;
}
private static int judgeIpAddr(String s) {
String[] ss = s.split("\\.");
if(ss.length != 4) {
return 0;
}
for(String str: ss) {
if(Integer.parseInt(str) > 255 || Integer.parseInt(str) < 0) {
return 0;
}
}
return 1;
}
private static Long ipConvertLong(String ip) {
Long ipt= 0L;
for(int i = 0; i < 4; i++) {
ipt = ipt << 8 | Integer.parseInt(ip.split("\\.")[i]);
}
return ipt;
}
}