题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
这个题目比较简单,思路:获取subnet,ip1,ip2,
先判断格式,如果其中有一个不符合正确的IP格式,或子网掩码不符合格式(子网掩码分4段,每段为8位,不够8位的前面补齐0,按子网掩码特征,M个连续的1,后面跟N个连续的0,如果有01出现则不符合格式),直接输出1;
如果都符合格式,subnet,ip1,ip2均分为4个整数分别进行&运算,运算结果完全一致则ip1,ip2为同一子网,否则不为同一子网。
import java.util.*; public class IpSubnet { public static void main(String[] args){ String subnet; String ip1; String ip2; Scanner in = new Scanner(System.in); while(in.hasNextLine()){ subnet = in.nextLine(); ip1 = in.nextLine(); ip2 = in.nextLine(); judge(subnet, ip1, ip2); } } private static void judge(String subnet, String ip1, String ip2) { if (!legalIP(subnet) || !legalSubNet(subnet) || !legalIP(ip1) || !legalIP(ip2)) { System.out.println("1"); } else { boolean flag = true; String[] subnetArr = subnet.split("\\."); String[] ip1Arr = ip1.split("\\."); String[] ip2Arr = ip2.split("\\."); for (int i = 0; i < 4; i++) {//分四组进行与操作,按照规则,同一子网中ip1与ip2分别跟subnet进行按位与的结果一样 if ((Integer.parseInt(subnetArr[i]) & Integer.parseInt(ip1Arr[i])) != (Integer.parseInt(subnetArr[i]) & Integer.parseInt(ip2Arr[i]))) { flag = false; }; } if (flag == true) { System.out.println("0"); } else { System.out.println("2"); } } } private static boolean legalSubNet(String subnet) {//判断合法子网 boolean correctSubnet = true; String[] subnetList = subnet.split("\\."); StringBuffer sb = new StringBuffer(); for (int i = 0; i < subnetList.length; i++) { String tmp = Integer.toBinaryString(Integer.parseInt(subnetList[i])); if (tmp.length() < 8) { for (int j = 0; j < 8 - tmp.length(); j++) { tmp = "0" + tmp; } } sb.append(tmp); } if (sb.toString().contains("01")) {//子网掩码为连续的M个1和后续连续的N个0 如果包含01则不为合法 correctSubnet = false; } return correctSubnet; } private static boolean legalIP(String ip) {//判断合法IP // String regex = "^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\." + // "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\." + // "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\." + // "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$"; // if (ip.matches(regex)) {//正则表达式判断合法IP // return false; // } String[] ipArr = ip.split("\\."); int first = Integer.parseInt(ipArr[0]); int second = Integer.parseInt(ipArr[1]); int third = Integer.parseInt(ipArr[2]); int fourth = Integer.parseInt(ipArr[3]); if ((first >= 1 && first <= 255) && (second >= 0 && second <= 255) && (third>= 0 && third <= 255) && (fourth >= 0 && fourth <= 255)) { return true; } return false; } }