判断ip地址是否合法(美团2024届秋招笔试第三场编程真题)

核心思想

大模拟 -。-,还是不够细心,面向样例编程,一路错过去的。

主要的想法还是转成int 数字再处理

请看注释
写得太丑了 凑合看吧。

代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        final long MOD = (long) (1e9 + 7);
        Scanner scanner = new Scanner(System.in);

        String s = scanner.nextLine();
        String[] split = s.split("\\.");
        boolean flag = true;
        //开头结尾必须是数字 防止字符开始结束
        if(s.charAt(0) < '0' || s.charAt(0) > '9' ||
                s.charAt(s.length() - 1) < '0' || s.charAt(s.length() - 1) > '9')
            flag = false;
        //拆分后的数组长度为4
        if (split.length != 4)
            flag = false;
        if(!flag){
            System.out.println("invalid");
            return;
        }
        // 将ip转换为数字
        int[] nums = new int[4];
        int idx = 0;
        for (String sp : split) {
            int cur = 0;
            char[] chs = sp.toCharArray();
            // 前导0 注意1.0.0.0 这样是允许的 要结合size判断 || 1.0..0 这样的数组长度也是4
            if((sp.startsWith("0") && sp.length() !=1) || chs.length == 0){
                flag = false;
                break;
            }
            // 必须是数字
            for (char ch : chs) {
                if(ch < '0' || ch > '9'){
                    flag = false;
                    break;
                }
                else
                    cur = cur * 10 + ch - '0';
            }
            nums[idx++] = cur;
        }
        if(!flag){
            System.out.println("invalid");
            return;
        }
        // 检查0-255范围
        if(!check(nums, 0, 255, 0, 255, 0, 255, 0, 255)){
            System.out.println("invalid");
        }
        // 地址分类
        else if(check(nums, 1, 126, 0, 0, 0, 0, 0, 0)){
            System.out.println("A_address");
        }
        else if(check(nums, 128, 191, 0, 255, 0, 255, 0, 255)){
            System.out.println("B_address");
        }
        else if(check(nums, 192, 223, 0, 255, 0, 255, 0, 255)){
            System.out.println("C_address");
        }
        else
            System.out.println("other");
    }
    
    // 判断4个num 是否符合范围
    static boolean check(int[] nums,int s0, int e0, int s1, int e1, int s2, int e2, int s3, int e3){
        // A类地址 第一位不是126时范围变化一下 我传入的start 和 end 都是0
        if(nums[0] != 126){
            e1 = e2 = e3 = 255;
        }
        if(nums[0] < s0 || nums[0] > e0)
            return  false;
        if(nums[1] < s1 || nums[1] > e1)
            return  false;
        if(nums[2] < s2 || nums[2] > e2)
            return  false;
        if(nums[3] < s3 || nums[3] > e3)
            return  false;
        return true;
    }
}
posted @ 2024-04-02 10:52  Shie1d  阅读(65)  评论(0)    收藏  举报