题解 | #整数与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 scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String num = scanner.nextLine();
        System.out.println(transferToInteger(str));
        long dexNum = Long.parseLong(num);
        System.out.println(transferToBinary(dexNum));
    }

    public static long transferToInteger(String str) {
        String[] strings = str.split("\\.");
        StringBuilder binaryString = new StringBuilder();
        for (String s : strings) {
            long num = Long.parseLong(s);
            String strBinary = Long.toBinaryString(num);
            while (strBinary.length() < 8) {
                strBinary = '0' + strBinary;
            }
            binaryString.append(strBinary);
        }
        return Long.parseLong(binaryString.toString(), 2);
    }

    public static String transferToBinary(long num) {
        String binaryString = Long.toBinaryString(num);
        while (binaryString.length() < 32) {
            binaryString = '0' + binaryString;
        }
        String str = "";
        for (int j = 0; j < 4; j++) {
            String subString = binaryString.substring(8 * j, 8 * j + 8);
            str = str + Long.parseLong(subString, 2);
            str += ".";
        }
        return str.substring(0, str.length()-1);
    }
}

全部评论

相关推荐

预计下个星期就能开奖吧,哪位老哥来给个准信
华孝子爱信等:对接人上周说的是这周
点赞 评论 收藏
分享
10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务