题解 | #整数与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);
        
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            String ip = scanner.next();
            long no = scanner.nextLong();
            StringBuilder builder = new StringBuilder();
            for (String s : ip.split("\\.")) {
                builder.append(dTob(s));
            }

            long num = 0;

            for (int i = 31,j=0; i >= 0; i--,j++) {
                if (builder.charAt(i) == '1') {
                    num += Math.pow(2, j);
                }
            }
            System.out.println(num);
            builder.delete(0, builder.length());

            while (no > 0) {
                long yu = no%2;
                builder.append(yu==0?"0":"1");
                no /=2;
            }
            int length = builder.length();
            if (length < 32) {
                for (int i = 0; i < 32-length; i++) {
                    builder.append("0");
                }
            }
            builder = builder.reverse();
            StringBuilder builder1 = new StringBuilder();
            for (int i = 0; i < 4; i++) {
                int res= 0;
                for (int j = i*8+7,k=0; j >= i*8; j--,k++) {
                    res += builder.charAt(j) == '0' ? 0 : Math.pow(2, k);
                }
                builder1.append(res);
                if (i<3) {
                    builder1.append(".");
                }
            }
            System.out.println(builder1);
        
    }
    }

    public static String dTob(String original) {
        int n = Integer.parseInt(original);
        StringBuilder builder = new StringBuilder();
        if (n<=1) return "0000000" + n;
        while (n>0) {
            int yu = n%2;
            builder.append(yu==0?"0":"1");
            n /= 2;
        }
        int length = builder.length();
        if (length < 8) {
            for (int i = 0; i < 8-length; i++) {
                builder.append(0);
            }
        }
        return builder.reverse().toString();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务