题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Collectors;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String nextLine = in.nextLine();
if (Objects.isNull(nextLine) || nextLine.equals("")) {
break;
}
// 示例:
// I P 地址 192.168.0.1
// 子网掩码 255.255.255.0
//
// 转化为二进制进行运算:
//
// I P 地址 11000000.10101000.00000000.00000001
// 子网掩码 11111111.11111111.11111111.00000000
//
// AND运算 11000000.10101000.00000000.00000000
//
// 转化为十进制后为:
// 192.168.0.0
//
//
// I P 地址 192.168.0.254
// 子网掩码 255.255.255.0
//
//
// 转化为二进制进行运算:
//
// I P 地址 11000000.10101000.00000000.11111110
// 子网掩码 11111111.11111111.11111111.00000000
//
// AND运算 11000000.10101000.00000000.00000000
//
// 转化为十进制后为:
// 192.168.0.0
//
// 通过以上对两台计算机IP地址与子网掩码的AND运算后,我们可以看到它运算结果是一样的。均为192.168.0.0,所以这二台计算机可视为是同一子网络。
try {
String ip1 = in.nextLine();
String ip2 = in.nextLine();
String ip1Str = transform(ip1);
String ip2Str = transform(ip2);
String dns = transform(nextLine);
valid(dns);
if ((Long.parseLong(ip1Str, 2) & Long.parseLong(dns,
2)) == (Long.parseLong(ip2Str, 2) & Long.parseLong(
dns, 2))) {
System.out.println(0);
} else {
System.out.println(2);
}
} catch (Exception exception) {
System.out.println(1);
}
}
}
public static void valid(String str) {
String regex = "[1]+[0]+";
if (str.matches(regex)) {
return;
}
throw new RuntimeException();
}
public static String transform(String str) {
String[] split = str.split("\\.");
String collect = Arrays.asList(split)
.stream()
.map(item -> {
int i = Integer.parseInt(item);
if (i < 0 || i > 255) {
throw new RuntimeException();
}
// 8位 左侧补0的工具
String toBinaryString = String.format("%08d",
Integer.parseInt(Integer.toBinaryString(Integer.parseInt(item))));
return toBinaryString;
})
.collect(Collectors.joining());
return collect;
}
}
