/* * 解题思路: * 1. ip转整形: 字符串切割后转二进制, 并拼接计算 * 2. 整形转ip: 转换成二进制, 按8位进行位运算即可 * 其它笔记: * 1. java二进制的转换和表示(String类型表示) * 1) 2->10 Integer.parseUnsignedInt(string, 2); * 2) 10->2 Integer.toBinaryString(int); * 提交失败: * 1. int tmpInt = Integer.parseInt(ip); // 数组越界, 没有给出失败用例, 原因不明, 尝试换成parseUnsignedInt() * 2. 3/10 组用例通过, 原因: 转换结果大于int最大值, 转换为unsigned long类型 */ import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { System.out.println(ip2int(sc.nextLine())); System.out.println(int2ip(sc.nextLine())); } } static long ip2int(String ip) { String[] strs = ip.split("[.]+"); StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { // 这里不用转long类型, 因为二进制转换本身就是无符号操作 int tmpInt = Integer.parseUnsignedInt(strs[i]); String tmpBin = Integer.toBinaryString(tmpInt); for (int j = 8 - tmpBin.length(); j > 0; j--) { tmpBin = "0" + tmpBin; } sb.append(tmpBin); } int tmpRes = Integer.parseUnsignedInt(sb.toString(), 2); return Integer.toUnsignedLong(tmpRes); } static String int2ip(String ip) { StringBuffer sb = new StringBuffer(); int tmpInt = Integer.parseUnsignedInt(ip); String tmpBin = Integer.toBinaryString(tmpInt); for (int i = 32 - tmpBin.length(); i >0; i--) { tmpBin = "0" + tmpBin; } for (int i = 0; i < 4; i++) { // 这里也不用转, 总共就4字节 int tmpIp = Integer.parseUnsignedInt(tmpBin.substring(i * 8, i * 8 + 8), 2); sb.append(tmpIp); if (i != 3) { sb.append("."); } } return sb.toString(); } }