题解 | #合法IP#

合法IP

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String line = in.nextLine();
            String[] s = line.split("\\.");
            int count = 0;

            if (s.length != 4) {
                count++;
            }
            for (int i = 0; i < s.length; i++) {
                if (s[i].length() <= 0) {
                    count++;
                } else if (s[i].startsWith("0") && s[i].length() > 1) {
                    count++;
                } else if (s[i].matches(".*[^0-9].*")) {
                    count++;
                } else if (Integer.parseInt(s[i]) < 0 || Integer.parseInt(s[i]) > 255) {
                    count++;
                }
            }
            if (count != 0) {
                System.out.println("NO");
            } else {
                System.out.println("YES");
            }
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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