1. 题目
读题
考查点
2. 解法
思路
二进制与十进制的互转
代码逻辑
具体实现
public class IP2Num {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.println(convertIp10(sc.nextLine()));
System.out.println(convertIp(sc.nextLine()));
}
}
public static long convertIp10(String ip) {
String[] ips = ip.split("\\.");
StringBuffer sb = new StringBuffer();
for (String cur : ips) {
sb.append(binStr(cur));
}
return Long.parseLong(sb.toString(), 2);
}
private static String binStr(String s) {
StringBuffer sb = new StringBuffer();
int num = Integer.parseInt(s);
int k = 1 << 7;
for (int i = 0; i < 8; i++) {
int flag = (num & k) == 0 ? 0 : 1;
sb.append(flag);
num = num << 1;
}
return sb.toString();
}
public static String convertIp(String ip10) {
StringBuffer sb = new StringBuffer();
String ip2 = Long.toBinaryString(Long.parseLong(ip10));
String as = "";
for (int i = 0; i < 32 - ip2.length(); i++) {
as = as + "0";
}
ip2 = as + ip2;
for (int i = 0; i < ip2.length(); i = i + 8) {
sb.append(Long.parseLong(ip2.substring(i, i + 8), 2)).append(".");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
}