题解 | #判断两个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); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String ym = in.nextLine(); String ip1 = in.nextLine(); String ip2 = in.nextLine(); if (!(ipTest(ip1) && ipTest(ip2) && ymTest(ym))) { System.out.println("1"); continue; } String m = invert(ip1, ym); String n = invert(ip2, ym); if (!m.equals(n)) { System.out.println("2"); } else { System.out.println("0"); } } } public static String invert(String ip, String ym) { String[] ips = ip.split("\\."); String[] yms = ym.split("\\."); StringBuilder sum = new StringBuilder(); for (int i = 0; i < 4; i++) { int a = Integer.parseInt(ips[i]); int b = Integer.parseInt(yms[i]); int c = a & b; sum.append(c); if (i != 3) { sum.append("."); } } return sum.toString(); } public static boolean ipTest(String ip) { String[] ips = ip.split("\\."); for (int i = 0; i < ips.length; i++) { int a = Integer.parseInt(ips[i]); if (a < 0 || a > 255) { return false; } } return true; } public static boolean ymTest(String ym) { String[] yms = ym.split("\\."); StringBuilder sum = new StringBuilder(); for (int i = 0; i < yms.length; i++) { int a = Integer.parseInt(yms[i]); if (a < 0 || a > 255) { return false; } String s = Integer.toBinaryString(a); while (s.length() < 8) { s = "0" + s; } sum.append(s); } if (!sum.toString().matches("[1]{1,}[0]{1,}")) { return false; } return true; } }