题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String ip1 = scanner.nextLine(); String ip2 = scanner.nextLine(); // 10.0.3.193 => 167773121 String[] array1 = ip1.split("\\."); StringBuilder stringBuilder = new StringBuilder(); for (String s : array1) { String str = "00000000" + Long.toBinaryString(Long.parseLong(s)); str = str.substring(str.length() - 8); stringBuilder.append(str); } System.out.println(Long.parseLong(stringBuilder.toString(), 2)); // 167969729 => 10.3.3.193 // 1010 00000011 00000011 11000001 String str = "00000000000000000000000000000000" + Long.toBinaryString(Long.parseLong(ip2)); str = str.substring(str.length() - 32); StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < str.length(); i = i + 8) { int a = Integer.parseInt(str.substring(i, i + 8), 2); stringBuilder2.append(a).append("."); } System.out.println(stringBuilder2.substring(0, stringBuilder2.length() - 1)); } }