题解 | #整数与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 sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        while (sc.hasNext()) {
            String ip = sc.nextLine().replaceAll(" ", "");
            String num = sc.nextLine().replaceAll(" ", "");
            String[] strings = ip.split("\\.");
            for (String string : strings) {
                String binary = Integer.toBinaryString(Integer.parseInt(string));
                sb.append(String.format("%08d", Integer.parseInt(binary)));
            }
            System.out.println(Long.parseLong(sb.toString(),2));
            sb.delete(0, sb.length());

            String b = Long.toBinaryString(Long.parseLong(num));
            String binary = String.format("%32s", b).replace(" ", "0");
            sb.append(Integer.parseInt(binary.substring(0, 8), 2)).append(".")
            .append(Integer.parseInt(binary.substring(8, 16), 2)).append(".")
            .append(Integer.parseInt(binary.substring(16, 24), 2)).append(".")
            .append(Integer.parseInt(binary.substring(24), 2));
            System.out.println(sb);
            sb.delete(0, sb.length());
        }
    }
}

全部评论

相关推荐

ResourceUtilization:差不多但是估计不够准确,一面没考虑到增长人口,另一方面也没考虑到能上大学的人数比例,不过我猜肯定只多不少
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务