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

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

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            IpMask mask = new IpMask(in.nextLine());
            IpMask ip1 = new IpMask(in.nextLine());
            IpMask ip2 = new IpMask(in.nextLine());
            if(!mask.maskIsValid() || !ip1.ipIsValid() || !ip2.ipIsValid()){
                System.out.println(Result.INVALID);
                continue;
            }
            long maskt = mask.getLong();
            long ipt1 = ip1.getLong();
            long ipt2 = ip2.getLong();
            if((maskt&ipt1) == (maskt&ipt2)){
                System.out.println(Result.SAME);
            }else{
                System.out.println(Result.NOT);
            }
        }
    }

    // 结果定义
    private static class Result{
        static int INVALID = 1;
        static int SAME = 0;
        static int NOT = 2;
    }

    // IpMask类定义
    private static class IpMask{
        public int[] a;

        public IpMask(String s){
            String[] ss = s.split("[.]+");
            this.a = new int[ss.length];
            for(int i=0; i<this.a.length; i++){
                this.a[i] = Integer.valueOf(ss[i]);
            }
        }

        // IP是否合法
        public boolean ipIsValid(){
            if(this.a==null || this.a.length!=4){
                return false;
            }
            for(int x : this.a){
                if(x<0 || x>255){
                    return false;
                }
            }
            return true;
        }

        // mask是否合法
        public boolean maskIsValid(){
            if(!ipIsValid()){
                return false;
            }
            StringBuilder sb = new StringBuilder();
            for(int x : this.a){
                sb.append(String.format("%8s", Integer.toBinaryString(x))
                    .replaceAll(" ", "0"));
            }
            int last1 = sb.lastIndexOf("1");
            int fist0 = sb.indexOf("0");
            if(fist0==-1){// 全1
                return true;
            }else if(fist0 < last1){ // 11011
                return false;
            }else{// 11100
                return true;
            }
        }

        // IP地址转换为Long
        public long getLong(){
            long ans = 0;
            for(int x : this.a){
                ans = ans*256 + x;
            }
            return ans;
        }
    }
}

全部评论

相关推荐

03-08 18:11
门头沟学院 Java
Java抽象小篮子:海投就完事了,简历没什么问题,最大问题是学历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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