题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

import java.util.Scanner;

import java.util.Stack;

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

            System.out.println(solution(in.nextLine()));
        }
    }

    private static String solution(String param) {
        if (isIp(param)) {

            String[] ipArray = param.split("\\.");
            StringBuffer sbf = new StringBuffer();

            for (String ip : ipArray) {

                sbf.append(ten2two(ip));
            }
            return two2ten(sbf.toString());
        }

        String twoStr = ten2two(param);
        String[] twoArray = twoStr.split(" ");

        StringBuffer sbf = new StringBuffer();
        for (String two : twoArray) {
            sbf.append(two2ten(two));
            sbf.append(".");
        }
        sbf.deleteCharAt(sbf.length() - 1);
        return sbf.toString();
    }

    private static boolean isIp(String param) {
        if (param.indexOf(".") > 0) {
            return true;
        }
        return false;
    }

    private static String two2ten(String two) {

        long res = 0;
        int length = two.length();
        while (length > 0) {

            char num = two.charAt(length-1);
            if (num == '1') {
                res += Math.pow(2, two.length() - length);
            }
            length--;
        }
        return res + "";
    }

    private static String ten2two(String ten) {

        Stack<String> stack = new Stack<>();
        long a = Long.parseLong(ten);
        while (a > 1) {
            stack.add(a % 2 + "");
            a = a / 2;
        }
        stack.add(a + "");
   
        int pos = stack.size() % 8;
        if (pos != 0) {
            int zeroNum = 8 - pos;
            while (zeroNum > 0) {
                zeroNum--;
                stack.add("0");
            }
        }
        StringBuffer sbf = new StringBuffer();
        int stackSize = stack.size();
    
        int count = 1;
        while (!stack.isEmpty()) {
            sbf.append(stack.pop());

            if (count % 8 == 0) {
                sbf.append(" ");
            }
            count++;
        }
        sbf.deleteCharAt(sbf.length() - 1);
        return sbf.toString();
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务