题解 | 合法IP

合法IP

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] strs = str.split("\\.");
        boolean result = true;
	  // 长度必须是4
        if (strs.length != 4) {
            System.out.println("NO");
            return;
        }
        for (String s : strs) {
		  // 不能是 + 和 - 开头
            if(s.startsWith("+") || s.startsWith("-")) {
                 result = false;
                break;
            }
		  // 长度大于1不能是0开头
            if(s.length() > 1 && s.startsWith("0")) {
                result = false;
                break;
            }
            try {
			  // 转换成数据不能大于255
                if (Integer.parseInt(s) > 255) {
                    result = false;
                    break;
                }
            } catch (Exception e) {
                result = false;
                break;
            }
        }
        if (result) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }
}

全部评论

相关推荐

04-03 22:41
兰州大学 C++
老六f:有时候是HR发错了,我之前投的百度的后端开发,他给我发的算法工程师,但是确实面的就是百度开发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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