题解 | #合法IP#

合法IP

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

import java.util.Scanner;

import java.util.ArrayList;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static int test(String ip_v){
        if(ip_v.startsWith("0")&&ip_v.length()>1){
            return 0;
        }
        if(ip_v.startsWith("+")&&ip_v.length()>1){
            return 0;
        }
        if(ip_v.startsWith("-")&&ip_v.length()>1){
            return 0;
        }
        try{
            int a = Integer.parseInt(ip_v);
            if(a>=0 && a<=255){
                return 1;
            }else{
                return 0;
            }
        }catch(Exception e){
            return 0;
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.next();
            String[] b = a.split("\\.");

            if(b.length!=4){
                System.out.println("NO");
                break;
            }

            ArrayList<String> ip_list = new ArrayList<String>();
            for(String ip_v:b){               
                int tag = test(ip_v);
                if(tag==0){
                    System.out.println("NO");
                    System.exit(0);
                }
            }
            System.out.println("YES");
        }
    }
}

#学习笔记#
全部评论

相关推荐

某物流公司 软件开发岗 总包26-30
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务