题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
/*
* */
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ip = sc.next();
long l = sc.nextLong();
System.out.println(yip(ip));
System.out.println(dip(l));
}
//10进制转ip
private static String dip(long num){
String s = Long.toBinaryString(num);
String[] strings = new String[4];
while (s.length() < 32){
s = "0" + s;
}
for (int i = 0; i < 4; i++) {
String substring = s.substring(i * 8, i * 8 + 8);
int i1 = Integer.parseInt(substring, 2);
strings[i] = String.valueOf(i1);
}
return String.join(".",strings);
}
//ip转10进制
private static long yip(String str){
String[] split = str.split("[.]");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
int i1 = Integer.parseInt(split[i]);
String s = Integer.toBinaryString(i1);
while (s.length() < 8){
s = "0" + s;
}
sb.append(s);
}
return Long.parseLong(sb.toString(),2);
}
}