题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
思路 :主要是处理二进制与十进制之间的转换,二进制到十进制写一个函数getDecimal(String s)完成,十进制到二进制用Integer.toBinaryString()。Show me the Code:
import java.util.*; public class IPTransformer { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String ip = in.nextLine(); long decimal = Long.parseLong(in.nextLine()); System.out.println(ip2Decimal(ip)); System.out.println(decimal2IP(decimal)); } } private static String decimal2IP(long decimal) { String binary = Long.toBinaryString(decimal);//1010000000000000001111000001 StringBuffer sb = new StringBuffer(); String[] ipArray = new String[4]; int firstLen = binary.length() - 24;//第一位IP的字符串长度 ipArray[0] = binary.substring(0, firstLen); for (int i = 1; i < 4; i++) { ipArray[i] = binary.substring(firstLen + (i - 1) * 8, firstLen + i * 8);//IP后面三位 } for (int i = 0; i < 4; i++) { sb.append(getDecimal(ipArray[i])).append("."); } String result = sb.toString(); return result.substring(0, result.length() - 1); } private static long ip2Decimal(String ip) { String[] ipArray = ip.split("\\."); StringBuffer sb = new StringBuffer(); long decimal = 0; for (int i = 0; i < ipArray.length; i++) { String tmp = Integer.toBinaryString(Integer.parseInt(ipArray[i])); StringBuffer sb1 = new StringBuffer(); int len = tmp.length(); if (len < 8) {//每段IP转换成8位的二进制,长度不够8的前面补0 for (int j = 0; j < 8 - len; j++) { sb1.append("0"); } sb1.append(tmp); } else { sb1.append(tmp); } sb.append(sb1); } String tmp = sb.toString(); while (tmp.startsWith("0")) {//移除开头多余的0 tmp = tmp.substring(1); } decimal = getDecimal(tmp); return decimal; } private static long getDecimal(String tmp) {//从二进制字符串转换成十进制 long decimal = 0; char[] binary = tmp.toCharArray(); for (int i = 0; i < binary.length; i++) { decimal += Character.getNumericValue(binary[i]) * Math.pow(2, binary.length - i -1); } return decimal; } }