acwing_3634. IP地址

57 阅读1分钟

image.png

总结一下 : 不是 IP 地址的 情况 。 (输入十进制数)

  • 1、出现字母的情况
  • 2、类似于 192..1.1 前三个点是空串的情况
  • 3、十进制数 大于255 的情况
import java.util.*;
import java.io.*;

public class Main {
     public static void main(String[] args) {
            Scanner sc = new Scanner(new BufferedInputStream(System.in));
            String ip = sc.next();
            boolean check = check(ip);
            if (!check)
                System.out.println("Error");
            else System.out.println(transForm(ip));
        }

        static boolean check(String ip) {
            String[] strs =  ip.split("\\.");
            // 不是四个整数组成 返回 false
            if (strs.length > 4 || strs[0].equals("") || strs[0].charAt(0) == '0') return false;
            for(int i = 0 ; i < strs.length ; i ++ ){
                if (strs[i].equals("") && i != strs.length - 1) return false;
                if ( !Character.isDigit(strs[i].charAt(0))) return false;
                for (int j = 0 ; j < strs[i].length(); j ++ ) {
                    if (!Character.isDigit(strs[i].charAt(j))) return false;
                }
                int num = Integer.parseInt(strs[i]);
                if (num > 255 ) return  false;
            }
            return true;
        }

        static String transForm(String ip) {
            StringBuilder sb = new StringBuilder("0x");
            String[] strs =  ip.split("\\.");
            for (String s : strs) {
                sb.append(numToString(s));
            }
            if (strs.length < 4) sb.append("00");
            return sb.toString();
        }

        static String numToString(String s) {
            int num = Integer.parseInt(s);
            StringBuilder sb = new StringBuilder();
            if (num < 10) {
                sb.append(0).append((char)(num + '0'));
                return sb.toString();
            }
                while (num != 0) {
                int a = num % 16;
                char c ;
                // 变成 对应的 ascall 字符
                if (a >= 10) c = (char) ('A' + a - 10);
                else c = (char) (a + '0');
                sb.append(c);
                num /= 16;
            }
            return sb.reverse().toString();

        }
}

作者:zzmm
链接:https://www.acwing.com/file_system/file/content/whole/index/content/7664006/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。