题解 | #整数与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);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
long a = ipToInteger(str);
System.out.println(a);
String str2 = in.nextLine();
long b = Long.valueOf(str2);
System.out.println(integerToIp(b));
}
}
// 将ip地址转换为10进制的数
public static long ipToInteger(String ip) {
String[] tempStrArr = ip.split("\\.");
String binaryStr = "";
for (int i = 0; i < 4; i++) {
String tempStr = Integer.toBinaryString(Integer.valueOf(tempStrArr[i]));
while (tempStr.length() < 8) {
tempStr = "0" + tempStr;
}
binaryStr += tempStr;
}
long sum = 0;
for (int i = 0; i < 32; i++) {
sum += (binaryStr.charAt(i) - '0') * Math.pow(2, 31 - i);
}
return sum;
}
// 将十进制的数转换为ip地址
public static String integerToIp(long num) {
String binaryStr = Long.toBinaryString(num);
while (binaryStr.length() < 32) {
binaryStr = "0" + binaryStr;
}
int[] ipArr = new int[4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 8; j++) {
ipArr[i] += ((binaryStr.charAt(i * 8 + j) - '0') * Math.pow(2, 7 - j));
}
}
String result = "";
for (int i = 0; i < 4; i++) {
if (i < 3) {
result += (String.valueOf(ipArr[i]) + ".");
} else {
result += String.valueOf(ipArr[i]);
}
}
return result;
}
}
查看13道真题和解析