题解 | #整数与IP地址间的转换# 使用分割+二进制
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String tmp = null;
while ((tmp=bf.readLine())!=null && !tmp.equals("")) {
String[] strArr = tmp.split("\\.");
int len = strArr.length;
if(len>1){//ip地址
StringBuffer waitToAppend = new StringBuffer("");
for(int i=0;i<len;i++){
waitToAppend.append(getValue(false, strArr[i]));
}
System.out.println(Long.parseLong(waitToAppend.toString(), 2));
}else{//10进制IP地址
String[] rstArr = new String[4];
String twoRaStr = getValue(true, tmp);
for(int i=0;i<4;i++){
rstArr[i] = twoRaStr.substring(i*8, i*8+8);
rstArr[i] = String.valueOf(Integer.parseInt(rstArr[i], 2));
if(i != 3){
System.out.print(rstArr[i]+".");
}else{
System.out.print(rstArr[i]);
}
}
System.out.println();
}
}
bf.close();
}
public static String getValue(Boolean flag, String str){
String standardStr1 = "00000000";
String standardStr2 = "00000000000000000000000000000000";
long num = Long.parseLong(str);
StringBuffer strTmp = new StringBuffer("");
int len = 0;
while(num != 0){
strTmp.append(num%2+"");
num = num >>> 1;
len++;
}
if(flag == false){
strTmp.append(standardStr1.substring(0, 8-len));
}else{
strTmp.append(standardStr2.substring(0, 32-len));
}
return strTmp.reverse().toString();
}
}
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String tmp = null;
while ((tmp=bf.readLine())!=null && !tmp.equals("")) {
String[] strArr = tmp.split("\\.");
int len = strArr.length;
if(len>1){//ip地址
StringBuffer waitToAppend = new StringBuffer("");
for(int i=0;i<len;i++){
waitToAppend.append(getValue(false, strArr[i]));
}
System.out.println(Long.parseLong(waitToAppend.toString(), 2));
}else{//10进制IP地址
String[] rstArr = new String[4];
String twoRaStr = getValue(true, tmp);
for(int i=0;i<4;i++){
rstArr[i] = twoRaStr.substring(i*8, i*8+8);
rstArr[i] = String.valueOf(Integer.parseInt(rstArr[i], 2));
if(i != 3){
System.out.print(rstArr[i]+".");
}else{
System.out.print(rstArr[i]);
}
}
System.out.println();
}
}
bf.close();
}
public static String getValue(Boolean flag, String str){
String standardStr1 = "00000000";
String standardStr2 = "00000000000000000000000000000000";
long num = Long.parseLong(str);
StringBuffer strTmp = new StringBuffer("");
int len = 0;
while(num != 0){
strTmp.append(num%2+"");
num = num >>> 1;
len++;
}
if(flag == false){
strTmp.append(standardStr1.substring(0, 8-len));
}else{
strTmp.append(standardStr2.substring(0, 32-len));
}
return strTmp.reverse().toString();
}
}