题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.*;
import java.lang.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String[] sz = in.nextLine().split("\\.");
String[] ip1 = in.nextLine().split("\\.");
String[] ip2 = in.nextLine().split("\\.");
int[] ip1o = new int[4];
int[] ip2o = new int[4];
boolean bo[] = new boolean[4];
int out=0;
for (int i = 0; i < 4; i++) {
int szi10=Integer.parseInt(sz[i],10);
boolean bszi = (szi10>=0 && szi10<=255);
int ip1i10=Integer.parseInt(ip1[i],10);
boolean bip1i = (ip1i10>=0 && ip1i10<=255);
int ip2i10=Integer.parseInt(ip2[i],10);
boolean bip2i = (ip2i10>=0 && ip2i10<=255);
if((!bszi) || (!bip1i) || (!bip2i) ){out=1;break;}
sz[i] = Integer.toBinaryString(szi10);
int l1 = 8 - sz[i].length();
for (int k = 0; k < l1; k++) {
sz[i] = "0" + sz[i];
}
ip1[i] = Integer.toBinaryString(ip1i10);
int l2 = 8 - ip1[i].length();
for (int j = 0; j < l2; j++) {
ip1[i] = "0" + ip1[i];
}
ip2[i] = Integer.toBinaryString(ip2i10);
int l3 = 8 - ip2[i].length();
for (int m = 0; m < l2; m++) {
ip2[i] = "0" + ip2[i];
}
ip1o[i] = Integer.parseInt(sz[i], 2) & Integer.parseInt(ip1[i], 2);
ip2o[i] = Integer.parseInt(sz[i], 2) & Integer.parseInt(ip2[i], 2);
bo[i] = (ip1o[i] == ip2o[i]);
}
String ssz = sz[0]+sz[1]+sz[2]+sz[3];
if(out==1){
System.out.println(out);continue;
}else if(!ssz.matches("1+0+")){
System.out.println(1);continue;
}else if(ssz.matches("1+0+") && bo[0] && bo[1] && bo[2] && bo[3]){
System.out.println(0);continue;
}else if(!bo[0] || !bo[1] || !bo[2] || !bo[3]){
System.out.println(2);continue;
}
}
}
}
查看8道真题和解析
