题解 | #整数与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 sc = new Scanner(System.in); while (sc.hasNext()) { String ip = sc.nextLine(); long num = sc.nextLong(); intonum(ip); intoip(num); } } private static void intonum(String ip) { // Integer.parseInt(ip); // System.out.println(Integer.toString(Integer.parseInt(ip),2)); String[] str = new String[4]; str = ip.split("\\."); StringBuilder sb = new StringBuilder(); // 1010011 11000001 for (String s : str ) { String s1 = Integer.toString(Integer.parseInt(s), 2); while (s1.length() % 8 != 0) { s1 = "0" + s1; } sb.append(s1); } System.out.println(Long.parseLong(sb.toString(), 2)); // 10110111 00011111 01001011 00010110 } private static void intoip(long num) { String str = Long.toBinaryString(num); while (str.length() % 8 != 0) { str = "0" + str; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length() - 7; i = i + 8) { String tmp = str.substring(i, i + 8); int i1 = Integer.parseInt(tmp, 2); sb.append(i1); if (i != str.length() - 8) { sb.append("."); } } // String.format() // System.out.println(str); System.out.println(sb); // 1010000000000000001111000001 // 00001010000000000000001111000001 // 00001010000000000000001111000001 // 00001010000000000000001111000001 // String s=sc.nextLine(); // System.out.println(Integer.parseInt(s,2)); } }