题解 | #合法IP# 我的代码写的跟shit一样

合法IP

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

// TMD,普通形式的判断太麻烦了,给我学正则表达式
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            // 输入
            String ip = in.next();
            if (isValid(ip)) {

                System.out.println("YES");
            } else {
                System.out.println("NO");
            }
        }
    }
    public static boolean isValid(String s) {

        String[] split = s.split("\\.");
        //    长度为4
        if (split.length != 4) {

            return false;
        }
        //  每组字符串转化为数字,不能大于100
        try {
            // for (String str : split) {
            //     // 我认为此时可以考虑异常
            //     // 考虑首位为0,长度不为1
            //     if(str.length()>=2&&str.charAt(0)=='0'){
            //         return false;
            //     }
            //     int i = Integer.parseInt(str);
            //     // 考虑数值范围
            //     if (i > 255 || i < 0) {
            //         return false;
            //     }
            // }
            // 直接遍历每一个字符
            for(String str:split){
                // 如果是空串,返回错误
                if(str.equals("")){
                    return false;
                }
                for(int i=0;i<str.length();i++){
                    char c=str.charAt(i);
                    if(str.length()>=2&&i==0&&(c>'9'||c<='0')){
                        return false;
                    }
                if(c>'9'||c<'0'){
                        return false;
                    }
                }
                 int i = Integer.parseInt(str);
                 if(i>255||i<0){
                    return false;
                 }
            }

        } catch (NumberFormatException e) {
            return false;
        }


        return true;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
扉川川:查看图片
投递用友等公司10个岗位
点赞 评论 收藏
分享
08-20 12:08
门头沟学院 Java
有保底啦!!!
future0210:字节是保底吗[牛泪[笑着活下去]
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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