题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { for (int i = 0; i < 3; i++) { String yM = in.nextLine(); String ip1 = in.nextLine(); String ip2 = in.nextLine(); String[] yMArr = yM.split("\\."); String[] ip1Arr = ip1.split("\\."); String[] ip2Arr = ip2.split("\\."); boolean b = true; for(int n = 0; n < yMArr.length; n++){ String numStr = yMArr[n]; int ymSeInt = Integer.valueOf(numStr); if(ymSeInt < 0){ b = false; } if(ymSeInt > 255){ b = false; } } int yMInt = getIpInt(yMArr); String yMTemp = Integer.toBinaryString(yMInt); while(yMTemp.length() < 32){ yMTemp = 0 + yMTemp; } //yMTemp = String.format("%032d", yMTemp); int bJ = -1; for (int k = 0; k < yMTemp.length(); k++) { if (k + 1 >= yMTemp.length() - 1) { break; } if (yMTemp.charAt(k) != yMTemp.charAt(k + 1)) { bJ = k + 1; break; } } if (bJ != -1) { String s1 = yMTemp.substring(bJ); if (s1.contains("1")) { // 非法 b = false; } } if (!b || !checkIp(ip1Arr) || !checkIp(ip2Arr)) { // 非法 System.out.println(1); break; } int ip1Int = getIpInt(ip1Arr); int ip2Int = getIpInt(ip2Arr); if ((ip1Int & yMInt) == (ip2Int & yMInt)) { System.out.println(0); break; } else { System.out.println(2); break; } } } } private static boolean checkIp(String[] ipArr) { for (int i = 0; i < ipArr.length; i++) { String temp = ipArr[i]; int ip1Int = Integer.valueOf(temp); if (ip1Int < 0 || ip1Int >= 255) { return false; } } return true; } private static int getIpInt(String[] ipArr) { int resInt = 0; for (int i = 0; i < ipArr.length; i++) { String temp = ipArr[i]; int ip1Int = Integer.valueOf(temp); resInt += ip1Int << 8 * (3 - i); } return resInt; } }