题解 | #整数与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);
        while (in.hasNext()) {
            String ip = in.nextLine();
            if (ip.contains(".")) {
                String[] split = ip.split("\\.");
                String binary = "";
                for (String s : split) {
                    String format = String.format("%8s",
                                                  Integer.toBinaryString(Integer.parseInt(s))).replace(' ', '0');
                    binary = binary.concat(format);
                }
                System.out.println(Long.parseLong(binary, 2));
            } else {
                int[] index = new int[4];
                String binaryString = String.format("%32s",
                                                    Long.toBinaryString(Long.parseLong(ip))).replace(' ', '0');
                for (int i = 0; i < 4; i++) {
                    index[i] = Integer.parseInt(binaryString.substring(i * 8, 8 * (i + 1)), 2);
                }
                System.out.printf("%d.%d.%d.%d", index[0], index[1], index[2], index[3]);
            }
        }
    }
}

#2022牛客时光#
全部评论

相关推荐

程序员鼠鼠_春招版:都很烂大街,rpc也基本没人问,考研吧,不然就包装一段实习再去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务