题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // ip转长整数 String ip = in.nextLine(); String[] split = ip.split("\\."); long result = 0L; result += Long.parseLong(split[0]) << 24; result += Long.parseLong(split[1]) << 16; result += Long.parseLong(split[2]) << 8; result += Long.parseLong(split[3]); System.out.println(result); // 长整数转ip String longStr = in.nextLine(); long inputLong = Long.parseLong(longStr); StringBuilder binaryString = new StringBuilder(Long.toBinaryString(inputLong)); while (binaryString.length() < 32) { // 不够32位前面补0直到补够32位(关键就在这里-Long.toBinaryString()方法计算出的二进制以1开头,0开头会省略) binaryString.insert(0, "0"); } // 将二进制字符串转化成整数 int a = Integer.parseInt(binaryString.substring(0, 8), 2); int b = Integer.parseInt(binaryString.substring(8, 16), 2); int c = Integer.parseInt(binaryString.substring(16, 24), 2); int d = Integer.parseInt(binaryString.substring(24), 2); System.out.println(a + "." + b + "." + c + "." + d); } }#刷题#