题解 | #整数与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); String ipWithDot = in.nextLine(); Long ipNumber = in.nextLong(); System.out.println(ip2Number(ipWithDot)); System.out.println(number2Ip(ipNumber)); } public static long ip2Number(String ipWithDot){ String[] ipArray = ipWithDot.split("\\."); StringBuilder sb = new StringBuilder(); for (String s : ipArray) {// 转二进制 String str = Integer.toBinaryString(Integer.parseInt(s)); while(str.length()<8){// 补0 str = "0" + str; } sb.append(str); } return (Long.parseLong(sb.toString(),2)); } public static String number2Ip(long ipNumber){ // to 2 进制 String num = Long.toBinaryString(ipNumber); // while(num.length()<32){ // fill with 0 num = "0"+num; } int ip1 = Integer.parseInt(num.substring(0,8),2); int ip2 = Integer.parseInt(num.substring(8,16),2); int ip3 = Integer.parseInt(num.substring(16,24),2); int ip4 = Integer.parseInt(num.substring(24,32),2); return ip1+"."+ip2+"."+ip3+"."+ip4; } }
注意知识点:
- 用点. 进行分割时, 要加反斜杠。
- 十进制转换成二进制 用Long.toBinaryString(ipNumber) 或 Integer.toBinaryString(Integer.parseInt(s))
- 十进制转16: Integer.toHexString ()
- 十进制转8: Integer.toOctalString()
- 其它进制转十进制 用Integer.parseInt(n,2); 其中2 表示2进制, 如果是16进制则写16