题解 | #判断两个IP是否属于同一子网#

判断两个IP是否属于同一子网

http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218

不知道为什么,本地Eclipse调试运行还有牛客调试里面使用它的用例:

255.255.255.0
48.23.217.254
48.23.217.226

都能通过,并且能输出0。 但是在牛客网站上点击保存提交,就显示通不过,并且没有打印输出。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Date 2022年5月31日下午5:34:27
 *  A类地址从1.0.0.0到126.255.255.255;
	B类地址从128.0.0.0到191.255.255.255;
	C类地址从192.0.0.0到223.255.255.255;
	D类地址从224.0.0.0到239.255.255.255;
	E类地址从240.0.0.0到255.255.255.255
 * 
 */
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		List<String> in=new ArrayList<>();
		while (sc.hasNext()) {
			in.add(sc.nextLine());
		}
		/*in.add("255.255.255.0");
		in.add("48.23.217.254");
		in.add("48.23.217.226");*/
		ipSubnet(in);
	}
	
	static void ipSubnet(List<String> in) {
		//先对ip和网关进行校验	、网关都错了的话,ip地址就没必要校验了
		if (!validSubIp(in)) {
			System.out.println(1);
		}else {
			//判断ip1、ip2是否属于统一子网
			if (ipIsSubNet(in)) {
				System.err.println(0);
			}else {
				System.out.println(2);
			}
		}
	}
	
	static boolean validSubIp(List<String> in) {
		//网关校验
		String subNet=in.get(0);
		if (subNet.matches("(255){1}\\.(0|(255)){1}\\.(0|(255)){1}\\.0{1}")) {	//此处0或255任选一不能用[0|(255)]表示,因为[]会匹配每个字符是否是0或者255,显然string-255是一个整体,所以要用()
			if (subNet.lastIndexOf("255")>subNet.lastIndexOf("0")) {	//255在0之后
				return false;
			}	
		}else {
			return false;
		}
		//ip地址校验
		for (int i = 1; i <= 2; i++) {	//对ip1和ip2进行校验
			String ip=in.get(i);
			String[] ipPara=ip.split("\\.");
			for (int n = 0; n < ipPara.length; n++) {
				if (n==0) {	//ip的第一段的有效性校验	
					if (Integer.parseInt(ipPara[i])<1||Integer.parseInt(ipPara[i])>255) {
						return false;
					}
				}else {
					if (Integer.parseInt(ipPara[i])<0||Integer.parseInt(ipPara[i])>255) {
						return false;
					}
				}
			}
		}

		return true;	//所有验证都通过时,返回true	
	}
	
	
	static boolean ipIsSubNet(List<String> in) {
		//取值
		long subNet = 0,ip1 = 0,ip2 = 0;
		//将ip地址/子网掩码从256进制转为10进制整数
		for (int i = 0; i < 3; i++) {
			String addr256=in.get(i);
			String[] num256=addr256.split("\\.");
			
			long ipTen=0;
			for (int n=0;n<=3;n++) {
				ipTen=(long) (ipTen+Integer.parseInt(num256[n])*Math.pow(256, 3-n));
			}
			if (i==0) {	//如果是0,则为子网掩码
				subNet=ipTen;
			}else if (i==1) {	//1时为ip1
				ip1=ipTen;
			}else {			//2时为ip2
				ip2=ipTen;
			}
		}
		long ip1yu,ip2yu;
		ip1yu=ip1&subNet;
		ip2yu=ip2&subNet;
		if (ip1yu==ip2yu) {
			return true;
		}else {
			return false;
		}
		
	}

}

全部评论

相关推荐

02-28 13:25
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务