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

整数与IP地址间的转换

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

import java.util.Scanner;

// 注意类名必须为 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

            String str = in.nextLine();
            long a = ipToInteger(str);
            System.out.println(a);

            String str2 = in.nextLine();
            long b = Long.valueOf(str2);
            System.out.println(integerToIp(b));

        }
    }

    // 将ip地址转换为10进制的数
    public static long ipToInteger(String ip) {
        String[] tempStrArr = ip.split("\\.");

        String binaryStr = "";
        for (int i = 0; i < 4; i++) {
            String tempStr = Integer.toBinaryString(Integer.valueOf(tempStrArr[i]));
            while (tempStr.length() < 8) {
                tempStr = "0" + tempStr;
            }
            binaryStr += tempStr;
        }

        long sum = 0;
        for (int i = 0; i < 32; i++) {
            sum += (binaryStr.charAt(i) - '0') * Math.pow(2, 31 - i);
        }

        return sum;
    }

    // 将十进制的数转换为ip地址
    public static String integerToIp(long num) {
        String binaryStr = Long.toBinaryString(num);
        while (binaryStr.length() < 32) {
            binaryStr = "0" + binaryStr;
        }

        int[] ipArr = new int[4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 8; j++) {
                ipArr[i] += ((binaryStr.charAt(i * 8 + j) - '0') * Math.pow(2, 7 - j));
            }
        }

        String result = "";
        for (int i = 0; i < 4; i++) {
            if (i < 3) {
                result += (String.valueOf(ipArr[i]) + ".");
            } else {
                result += String.valueOf(ipArr[i]);
            }
        }

        return result;
    }

}

全部评论

相关推荐

05-08 23:17
门头沟学院 Java
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务