题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String sy = scanner.nextLine(); String sp1 = scanner.nextLine(); String sp2= scanner.nextLine(); //验证掩码与IP每一段在 0 - 255 之间 ArrayList<String> pd = new ArrayList<>(); pd.add(sy); pd.add(sp1); pd.add(sp2); boolean b = yanzheng1(pd); if (b){ String s=""; String[] split = sy.split("\\."); for (int i = 0; i <split.length; i++) { String rb = rb(split[i]); s=s+rb;//子网掩码32位2进制显示 } if (s.matches("[1]{1,}[0]{1,}")){ String reb = reb(sy, sp1); String reb2 = reb(sy, sp2); if(reb.equals(reb2)){ System.out.println("0"); }else { System.out.println("2"); } }else { System.out.println("1");//子网掩码不对 } }else { System.out.println("1");//0-255范围不对 } } } public static String rb(String s){//10进制转2进制,如果长度小于8则补位0 Integer integer = Integer.valueOf(s); String string = Integer.toString(integer, 2); HashMap<Integer, Integer> hm = new HashMap<>(); hm.put(0,string.length()); if (string.length()<8){ for (int i = 0; i <8-hm.get(0); i++) { string="0"+string; } } return string; } public static boolean match(String s){//验证0-255范围 Integer it = Integer.valueOf(s); if(it<0||it>255){ return false; } return true; } public static boolean yanzheng1(ArrayList<String> aa){//验证全部的12个字段的0-255范围 for (int i = 0; i < aa.size(); i++) { String s = aa.get(i); String[] split = s.split("\\."); if (split.length!=4){ return false; }else { for (int j = 0; j <split.length; j++) { boolean match = match(split[j]); if(!match){ return false; } } } } return true; } public static String reb(String s,String d){//传入ip返回2进制32位串 String[] split = s.split("\\."); String[] split2 = d.split("\\."); String st=""; for (int i = 0; i <split.length; i++) { String s1 = split[i]; String s2 = split2[i]; Integer it1 = Integer.valueOf(s1); Integer it2 = Integer.valueOf(s2); int i1 = it1 & it2; String s3 = String.valueOf(i1); st=st+s3+"."; } return st; } }