题解 | #验证IP地址#

验证IP地址

http://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

就是处理一下字符串

    public String solve (String IP) {
        // write code here

        if (IP == null && IP.length() == 0){
            return "Neither";
        }

        if (IP.contains(":")){

            String[] fields = IP.split(":");
            if (fields.length != 8){
                return "Neither";
            }

            for (String field : fields) {
                if (!isIPV6(field)){
                    return "Neither";
                }
            }

            return "IPv6";
        }else if (IP.contains(".")){

            String[] fields = IP.split("\\.");
            if (fields.length != 4){
                return "Neither";
            }

            for (String field : fields) {
                if (!isIPV4(field)){
                    return "Neither";
                }
            }

            return "IPv4";
        }else {
            return "Neither";
        }
    }

    private boolean isIPV6(String str){

        if (str.length() > 4 || str.length() == 0){
            return false;
        }

        try {
            int max = Integer.valueOf("FFFF",16);
            int num = Integer.valueOf(str, 16);

            if (num > max){
                return false;
            }

        }catch (NumberFormatException e){

            return false;
        }
        return true;
    }

    private boolean isIPV4(String str){

        if (str.length() == 0 || str.length() > 3){
            return false;
        }

        try {

            int n = str.length();
            int num = Integer.valueOf(str);

            if (num > 255 || num < 0){
                return false;
            }

            if (n == 3 && num < 100){
                return false;
            }

        }catch (NumberFormatException e){
            return false;
        }

        return true;
    }
全部评论

相关推荐

扭转乾坤_:现在企业都是学华为,一直通过丢池子里,最后捞
点赞 评论 收藏
分享
shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务