题解 | #整数与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 的区别
String ip = "";
Long numIn = -1L;
while (in.hasNextLine()) { // 注意 while 处理多个 case
//s.append(in.next());
if ("".equals(ip)) {
ip = in.nextLine();
} else if (numIn == -1) {
numIn = Long.valueOf(in.nextLine());
}
}
if (!"".equals(ip) && numIn > 0) {
String[] sp = ip.split("\\.");
int len = sp.length;
long sum = 0;
for (int i = 0; i < len; i++) {
int num = Integer.valueOf(sp[i]);
sum += to10(num, 4 - i);
}
System.out.println(sum);
String numtoip = numtoip(numIn);
System.out.println(numtoip);
ip = "";
numIn = -1L;
}
}
private static long to10(long num, int count) {
long base = 1;
switch (count) {
case 2:
base = 256;
break;
case 3:
base = 256 * 256;
break;
case 4:
base = 256 * 256 * 256;
break;
default:
}
return num * base;
}
private static String numtoip(long num) {
long b1 = 0, b2 = 0, b3 = 0, b4 = 0;
if (num < 256) {
b1 = num;
} else if (num < 256 * 256) {
b2 = num / 256;
b1 = num - 256 * b2;
} else if (num < 256 * 256 * 256) {
b3 = num / 256 / 256;
b2 = (num - 256 * 256 * b3) / 256;
b1 = num - 256 * 256 * b3 - 256 * b2;
} else {
b4 = num / 256 / 256 / 256;
b3 = (num - 256 * 256 * 256 * b4) / 256 / 256;
b2 = (num - 256 * 256 * 256 * b4 - 256 * 256 * b3) / 256;
b1 = num - 256 * 256 * 256 * b4 - 256 * 256 * b3 - 256 * b2;
}
return b4 + "." + b3 + "." + b2 + "." + b1;
}
}
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记
查看15道真题和解析