题解 | #整数与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 scanner = new Scanner(System.in); String str = scanner.nextLine(); String num = scanner.nextLine(); System.out.println(transferToInteger(str)); long dexNum = Long.parseLong(num); System.out.println(transferToBinary(dexNum)); } public static long transferToInteger(String str) { String[] strings = str.split("\\."); StringBuilder binaryString = new StringBuilder(); for (String s : strings) { long num = Long.parseLong(s); String strBinary = Long.toBinaryString(num); while (strBinary.length() < 8) { strBinary = '0' + strBinary; } binaryString.append(strBinary); } return Long.parseLong(binaryString.toString(), 2); } public static String transferToBinary(long num) { String binaryString = Long.toBinaryString(num); while (binaryString.length() < 32) { binaryString = '0' + binaryString; } String str = ""; for (int j = 0; j < 4; j++) { String subString = binaryString.substring(8 * j, 8 * j + 8); str = str + Long.parseLong(subString, 2); str += "."; } return str.substring(0, str.length()-1); } }