题解 | #合法IP#

合法IP

https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String input = in.nextLine();
            String replace = input.replaceAll("\\.", "");
            boolean isNo = false;
            for (int i = 0; i < replace.length(); i++) {
                if (replace.charAt(i) > '9' || replace.charAt(i) < '0') {
                    isNo = true;
                }
            }
            if (!isNo) {
                isNo = defIsNo(input);
            }
            if (isNo) {
                System.out.println("NO");
            } else {
                System.out.println("YES");
            }
        }
    }

    private static boolean defIsNo(String input) {
        String[] array = input.split("\\.", -1);
        if (array.length != 4)
            return true;
        for (String s : array) {
            if (s.isEmpty() || (s.startsWith("0") && s.length() > 1))
                return true;
            int ip = Integer.parseInt(s);
            if (ip < 0 || ip > 255) {
                return true;
            }
        }
        return false;
    }
}

全部评论

相关推荐

02-04 15:03
南昌大学 Java
想去三亚看海的迪恩在...:刚刚打电话了说不录取,收了学信网和身份证,入职的信息条都发给我了,这种不录取究竟何意味?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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