题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
/**********************************************************************************/
// IPv4 转 整数
String[] strs = scan.nextLine().split("\\.");
StringBuffer sb = new StringBuffer("");
for (String str : strs) {
sb.append(DecimalToBinary(str, 8));
}
System.out.println(BinaryToDecimal(new String(sb), 31));
/**********************************************************************************/
// 整数 转 IPv4
String decimal = scan.nextLine();
String binary = DecimalToBinary(decimal, 32);
System.out.println(BinaryToIPv4(binary));
}
public static String DecimalToBinary(String str, int k) {
long num = Long.valueOf(str);
StringBuffer sb = new StringBuffer("");
while (0 != num) {
sb.append(num % 2);
num /= 2;
}
while (sb.length() != k) {
sb.append("0");
}
sb.reverse();
return new String(sb);
}
public static long BinaryToDecimal(String str, int k) {
long ans = 0l;
String[] strs = str.split("");
for (int i = strs.length - 1; i > -1; i--) {
if (Integer.valueOf(strs[i]) == 1) {
ans += Math.pow(2, k - i);
}
}
return ans;
}
public static String BinaryToIPv4(String str) {
StringBuffer sb = new StringBuffer("");
for (int splitIndex = 8; splitIndex <= 32; splitIndex += 8) {
String tmp = str.substring(splitIndex - 8, splitIndex);
if (splitIndex == 32) {
sb.append(BinaryToDecimal(tmp, 7));
break;
}
tmp = BinaryToDecimal(tmp, 7) + ".";
sb.append(tmp);
}
return new String(sb);
}
}