题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String mask = bf.readLine(); String ip1 = bf.readLine(); String ip2 = bf.readLine(); // 判断子网掩码是否合法 StringBuffer sb = new StringBuffer(); for(String str : mask.split("\\.")){ String binaryString = Integer.toBinaryString(Integer.parseInt(str)); if(binaryString.length() > 8){ System.out.println(1); return; } while(binaryString.length() < 8){ binaryString = "0" + binaryString; } sb.append(binaryString); } String maskBinaryString = sb.toString(); if(maskBinaryString.indexOf("0") < maskBinaryString.lastIndexOf("1")){ System.out.println(1); return; } // 判断ip1是否合法 StringBuffer sbIp1 = new StringBuffer(); for(String str : ip1.split("\\.")){ int ip1s = Integer.parseInt(str); if(ip1s < 0 || ip1s > 255){ System.out.println(1); return; } String binaryString = Integer.toBinaryString(ip1s); while(binaryString.length() < 8){ binaryString = "0" + binaryString; } sbIp1.append(binaryString); } // 判断ip2是否合法 StringBuffer sbIp2 = new StringBuffer(); for(String str : ip2.split("\\.")){ int ip2s = Integer.parseInt(str); if(ip2s < 0 || ip2s > 255){ System.out.println(1); return; } String binaryString = Integer.toBinaryString(ip2s); while(binaryString.length() < 8){ binaryString = "0" + binaryString; } sbIp2.append(binaryString); } // 都合法则进行位运算 Long maskLong = Long.parseLong(maskBinaryString, 2); Long ip1Long = Long.parseLong(sbIp1.toString(), 2); Long ip2Long = Long.parseLong(sbIp2.toString(), 2); if((maskLong & ip1Long) == (maskLong & ip2Long)){ System.out.println(0); } else { System.out.println(2); } } }