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

整数与IP地址间的转换

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ipStr = sc.nextLine();
        long decimal = sc.nextLong();
        long sum = getSum(ipStr);
        System.out.println(sum);
        String binaryStr = Long.toBinaryString(decimal);
        while (binaryStr.length() < 32) {
            binaryStr = 0 + binaryStr;
        }
        for (int i = 0; i < 4; i++) {
            String subBinary = binaryStr.substring(i * 8, (i + 1) * 8);
            Integer integer = Integer.valueOf(subBinary, 2);
            if (i == 3) {
                System.out.print(integer);
            } else {
                System.out.print(integer + ".");
            }
        }
    }

    private static long getSum(String ipStr) {
        String[] split = ipStr.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            int parseInt = Integer.parseInt(s);
            String binary = Integer.toBinaryString(parseInt);
            int binaryLength = binary.length();
            if (binaryLength < 8) {
                for (int i = 0; i < 8 - binaryLength; i++) {
                    sb.append(0);
                }
            }
            sb.append(binary);
        }
        String convertStr = sb.toString();
        long sum = 0;
        for (int i = convertStr.length() - 1, j = 0; i >= 0; i--, j++) {
            if (convertStr.charAt(i) == '0') {
                continue;
            }
            int digit = Integer.parseInt(String.valueOf(convertStr.charAt(i)));
            sum += (long) Math.pow(2, j) * digit;
        }
        return sum;
    }

}

全部评论

相关推荐

宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务