题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner; // 此类题比较复杂,多写几个函数这样好debug,看上去也清楚一些 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()){ String mask = sc.nextLine(); String ip1 = sc.nextLine(); String ip2 = sc.nextLine(); if(!areLegalMaskAndIps(mask,ip1,ip2)){ System.out.println(1); continue; } //记住split()是正则匹配,匹配'.'的时候要加转义符\,又因为是在“”中,还要再加一个转义符 //来转义转义符\ String[] maskSeqs = mask.split("\\."); String[] ip1Seqs = ip1.split("\\."); String[] ip2Seqs = ip2.split("\\."); int error=0; for(int i=0;i<4;i++){ int num = Integer.parseInt(maskSeqs[i]); int num1 = Integer.parseInt(ip1Seqs[i]); int num2 = Integer.parseInt(ip2Seqs[i]); int result1 = num&num1; int result2 = num&num2; if(result1!=result2){ error++; break; } } if(error==0){ System.out.println(0); } else{ System.out.println(2); } } } public static boolean areLegalMaskAndIps(String mask,String ip1,String ip2){ String[] maskSeqs = mask.split("\\."); String[] ip1Seqs = ip1.split("\\."); String[] ip2Seqs = ip2.split("\\."); if(maskSeqs.length!=4||ip1Seqs.length!=4||ip2Seqs.length!=4){ return false; } for(int i=0;i<4;i++){ int num = Integer.parseInt(maskSeqs[i]); int num1 = Integer.parseInt(ip1Seqs[i]); int num2 = Integer.parseInt(ip2Seqs[i]); if(num>255||num1>255||num2>255||num<0||num1<0||num2<0){ return false; } } //mask有一个特殊的地方需要判定,那就是他是左1,右0的形式,1不能出现在0之后 //否则就是非法的,设想的算法是找到最后一个1的索引,截取之前的子串,只要其中含有‘0’,那就非法 String maskInBinary = getBinaryString(maskSeqs); String subStr = maskInBinary.substring(0,maskInBinary.lastIndexOf('1')+1);//1加不加都一样 if(subStr.contains("0")){ return false; } return true; } public static String getBinaryString(String[] strs){ StringBuilder sb = new StringBuilder(); for(int i=0;i<4;i++){ int num = Integer.parseInt(strs[i]); String s = Integer.toBinaryString(num); //趁没人,补个零先,不然后续计算会出错 while(s.length()<8){ s = '0'+s; } sb.append(s); } return sb.toString(); } }