题解 | #整数与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牛客时光#