rambless
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
// 注意类名必须为 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 str1 = in.nextLine();
String str2 = in.nextLine();
String[] arr1 = str1.split("\\.");
String value1 = "";
for (int i = 0; i < arr1.length; i++) {
String temp1 = "";
int a = Integer.parseInt(arr1[i]);
while (a != 0) {
temp1 += a % 2;
a = a / 2;
}
//翻转补全
value1 += reverse(temp1, 8);
}
long total1 = toTen(value1);
System.out.println(total1);
long value2 = Long.parseLong(str2);
String temp2 = "";
while(value2!=0) {
temp2 += value2%2;
value2 /= 2;
}
//翻转补全
temp2 = reverse(temp2, 32);
long total2;
for(int i=0; i<4; i++) {
total2 = toTen(temp2.substring(i*8, (i+1)*8));
System.out.print(total2);
if(i<3) {
System.out.print(".");
}
}
}
}
private static long toTen(String value) {
long total = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '1') {
if (i == value.length() - 1) {
total += 1;
} else {
long v1 = 2;
for (int j = 1; j < value.length() - i - 1; j++) {
v1 *= 2;
}
total += v1;
}
}
}
return total;
}
private static String reverse(String temp, int len) {
Deque<String> stack = new LinkedList<>();
for (int i = 0; i < temp.length(); i++) {
stack.push(temp.substring(i, i + 1));
}
String back = "";
while (!stack.isEmpty()) {
back += stack.poll();
}
String less = "";
if (back.length() < len) {
for (int j = 0; j < len - back.length(); j++) {
less += "0";
}
}
return less + back;
}
}
查看4道真题和解析