题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); List<String> s = new ArrayList<>(); while (in.hasNextLine()) { s.add(in.nextLine()); } //分组循环,3行为一组 for (int i = 0; i < s.size(); i++) { if ((i + 1) % 3 == 0) { int num = judge(s.get(i - 2), s.get(i - 1), s.get(i)); System.out.println(num); } } } public static int judge(String netmask, String ip1, String ip2) { int result = 110; //判断输入合法性(数字在[0,255]) boolean flag = true; for (int i = 0; i < 4; i++) { flag = judgeNum(netmask.split("\\.")[i]); if (flag == false) { return 1; } flag = judgeNum(ip1.split("\\.")[i]); if (flag == false) { return 1; } flag = judgeNum(ip2.split("\\.")[i]); if (flag == false) { return 1; } } //判断子网掩码正确性,必须是连续的1和0 boolean flag1 = true; for (int i = 0; i < 4; i++) { String j = Integer.toBinaryString(Integer.parseInt(netmask.split("\\.")[i])|1<<8).substring(1); if (flag1 == true) { if (j.contains("0")) { flag1 = false; int index = j.indexOf("0",0); if(j.substring(index).contains("1")){ return 1; } } }else{ if(j.contains("1")){ return 1; } } } //判断是否属于同一子网 if (toBinary(netmask, ip1).toString().equals(toBinary(netmask, ip2).toString())) { return 0; } return 2; } public static StringBuffer toBinary(String s, String t) { String[] sArray = s.split("\\."); String[] tArray = t.split("\\."); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 4; i++) { int f = Integer.parseInt(sArray[i]) & Integer.parseInt(tArray[i]); sb.append(Integer.toBinaryString(f | 1 << 8)); } return sb; } public static boolean judgeNum(String s) { if (Integer.parseInt(s) >= 0 && Integer.parseInt(s) < 256) { return true; } return false; } }