题解 | 整数与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);
while (in.hasNext()) {
String str = in.next();
String res = getResult(str);
System.out.println(res);
}
}
public static String getResult(String str) {
if (str.indexOf(".") > 0) {
String[] split = str.split("\\.");
Long result = 0L;
int pow = 0;
for (int i = 3; i >= 0; i--) {
result += Long.parseLong(split[i]) * (int) Math.pow(256, pow++);
}
return String.valueOf(result);
} else {
long result = Long.parseLong(str);
StringBuilder builder = new StringBuilder();
int pow = 3;
while (result > 0) {
long num = result / (int)Math.pow(256, pow);
builder.append(num).append(".");
result = result % (int)Math.pow(256, pow);
pow--;
}
return builder.substring(0, builder.length() - 1);
}
}
}
查看1道真题和解析