题解 | #整数与IP地址间的转换#--字符串+数组操作
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String[] strs = in.nextLine().split("\\.");
long decNum = Long.parseLong(in.nextLine());
// ip转化为整数
StringBuffer sb = new StringBuffer();
for (String str : strs) {
int tem = Integer.parseInt(str);
sb.append(String.format("%8s", Integer.toBinaryString(tem)).replace(" ", "0"));
}
System.out.println(getInteger(sb.toString()));
// 整数转ip
String binaryStr = String.format("%32s",
Long.toBinaryString(decNum)).replace(" ", "0");
StringBuffer bf = new StringBuffer();
for (int i = 0; i < binaryStr.length() / 8; i++) {
bf.append(getInteger(binaryStr.substring(8 * i, 8 * (i + 1))) + ".");
}
System.out.println(bf.toString().substring(0, bf.length() - 1));
}
}
private static long getInteger(String binaryStr) {
long res = 0;
char[] chrs = binaryStr.toCharArray();
for (int i = chrs.length - 1; i >= 0; i--) {
if (chrs[i] == '1') {
res += Math.pow(2, binaryStr.length() - 1 - i);
}
}
return res;
}
}
