题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
不知道为什么这道题必须要用Long才行
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
String[] strs = str.split("\\.");
StringBuilder strb = new StringBuilder();
for(String s : strs){
s = Integer.toString(Integer.parseInt(s) ,2);
while(s.length()<8){
s = "0"+s;
}
strb.append(s);
}
Long n = Long.parseLong(strb.toString(),2);
System.out.println(n);
String s1 = scan.nextLine();
// String s2 = Integer.toString(Integer.parseInt(s1) ,2);
String s2 = Long.toString(Long.parseLong(s1),2);
while(s2.length()<32){
s2 = "0"+s2;
}
int[] nums = new int[s2.length()/8];
for(int i = 0; i<s2.length()/8; i++){
nums[i] = Integer.parseInt(s2.substring(8*i, 8*i+8),2);
}
for(int i = 0; i<nums.length-1; i++){
System.out.print(nums[i]+".");
}
System.out.print(nums[nums.length-1]);
}
scan.close();
}
}