HJ90 合法IP | 题解

将地址分为多个块,然后逐块进行验证。仅当每个块都有效时,该地址才有效。这种方法称为 分治法
通过界定符将地址分为四块,对于地址的每一块,检查它们是否在 0 - 255 内,且没有前置零。
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String[] nums = in.next().split("\\.", -1);
            String res = "YES";
            if (nums.length == 4) {
                for (String num : nums) {
                    if (num.length() == 0 || num.length() > 3) {
                        res = "NO";
                        break;
                    }
                    if (num.charAt(0) == '0' && num.length() != 1) {
                        res = "NO";
                        break;
                    }
                    for (char ch : num.toCharArray()) {
                        if (!Character.isDigit(ch)) {
                            res = "NO";
                            break;
                        }
                    }
                    if (Integer.parseInt(num) > 255) {
                        res = "NO";
                        break;
                    }
                }
            } else
                res = "NO";
            System.out.println(res);
        }
    }
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
07-16 18:03
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
07-03 16:13
嘉应学院 Python
xiaolihuam...:很明显骗子,如果是hr直接约你面试了,哪用得着内推,如果是员工的话,你得多优秀,一线员工直接加你微信,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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