【华为机试】HJ90 合法IP

IPV4地址可以用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此正号不需要出现),如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。 现在需要你用程序来判断IP是否合法。
数据范围:数据组数: 进阶:时间复杂度:,空间复杂度:

输入描述:
输入一个ip地址,保证不包含空格

输出描述:
返回判断的结果YES or NO
示例1
输入
255.255.255.1000
输出
NO

  • 思路分析

将ipv4字符串按.拆分成字符数组,使用split("\\.")
对字符数组中的每个字符串进行判断
判断ip的值是否为空 s.length() == 0,为空则直接退出,否则则继续验证合法性
将值转换为int类型,用于数值大小判断,范围是0~255 s.equals(a +"") 整数a+""就转换成字符串了
判断01这种string类型转换为int异常的情况。01肯定是错误的ip

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            ipv4(str);
        }
    }
    public  static void ipv4(String str) {
        int count = 0;
        String[] strArr = str.split("\\.");
        for (String s : strArr) {
            if (s.length() == 0) {
                break;
            } else {
                int a = Integer.parseInt(s);
                if (s.equals(a +"")) { 
                    //把a转成字符串判断和s是否相等 023和23不相等,0和0相等
                    if (a >=0 && a <= 255) {
                        count++;
                    } else {
                        break;
                    }
                }
            }
        }
        if (count == 4) {
            System.out.print("YES");
        } else {
            System.out.print("NO");
        }
    }
}


你可能感兴趣的:(华为机试【牛客网】,华为,tcp/ip,java)