题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner; // 都挤在一块哈哈 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String mask = in.nextLine(); String ip1 = in.nextLine(); String ip2 = in.nextLine(); String[] maskArr = mask.split("\\."); String[] ip1Arr = ip1.split("\\."); String[] ip2Arr = ip2.split("\\."); if (maskArr.length != 4 || ip1Arr.length != 4 || ip2Arr.length != 4) { System.out.println(1); continue; } StringBuilder sb = new StringBuilder(); int temp = 0; for (int j = 0; j < 4; j++) { if (Integer.parseInt(ip1Arr[j]) > 255 || Integer.parseInt(ip1Arr[j]) < 0 || Integer.parseInt(ip2Arr[j]) > 255 || Integer.parseInt(ip2Arr[j]) < 0 || Integer.parseInt(maskArr[j]) > 255 || Integer.parseInt(maskArr[j]) < 0) { System.out.println(1); temp = 1; break; } String binary = Integer.toBinaryString(Integer.parseInt(maskArr[j])); //不足8位补齐 binary = String.format("%08d", Integer.parseInt(binary)); sb.append(binary); } if (temp != 0) { continue; } if (sb.lastIndexOf("1") > sb.indexOf("0")) { System.out.println(1); continue; } for (int x = 0; x < 4; x++) { if ((Integer.parseInt(ip1Arr[x]) & Integer.parseInt(maskArr[x])) != (Integer.parseInt(ip2Arr[x]) & Integer.parseInt(maskArr[x]))) { System.out.println(2); temp = 1; break; } } if (temp != 0) { continue; } System.out.println(0); } } }