判断两个IP是否属于同一子网
判断两个IP是否属于同一子网
http://www.nowcoder.com/questionTerminal/34a597ee15eb4fa2b956f4c595f03218
import java.util.*; public class Main { public static void mian(String[] args){ Scanner sc = new Scanner(System.in); int[] ip1AfterHex = new int[4]; int[] ip2AfterHex = new int[4]; int[] subnetAfterHex = new int[4]; while(sc.hasNext()){ String subnetMask = sc.nextLine(); String ip1 = sc.nextLine(); String ip2 = sc.nextLine(); String[] subnetArray = subnetMask.split("\\."); String[] ip1Array = ip1.split("\\."); String[] ip2Array = ip2.split("\\."); for(int i=0;i<4;i++){ String xs = Integer.toBinaryString(Integer.parseInt(ip1Array[i])); String ys = Integer.toBinaryString(Integer.parseInt(ip2Array[i])); String zs = Integer.toBinaryString(Integer.parseInt(subnetArray[i])); ip1AfterHex[i]=Integer.parseInt(xs); ip2AfterHex[i]=Integer.parseInt(ys); subnetAfterHex[i]=Integer.parseInt(zs); } if(!isIp(ip1AfterHex)||!isIp(ip2AfterHex)||!isAd(subnetAfterHex)){ System.out.println(1); continue; } boolean flag=true; for(int i=0;i<4;i++){ if((ip1AfterHex[i]&subnetAfterHex[i])!=(ip2AfterHex[i]&subnetAfterHex[i])){ System.out.println(2); flag=false; break; } } if(flag) System.out.println(0); } } public static boolean isAd(int[] a){ return a[0]>=0&&a[0]<=255&& a[1]>=0&&a[1]<=255&& a[2]>=0&&a[2]<=255&& a[3]>=0&&a[3]<=255&& a[0]>=a[1]&& a[1]>=a[2]&& a[2]>=a[3]; } public static boolean isIp(int[] a){ return a[0]>=0&&a[0]<=255&& a[1]>=0&&a[1]<=255&& a[2]>=0&&a[2]<=255&& a[3]>=0&&a[3]<=255; } }