IP地址是一个用 '.' 隔开的四段数字,每段的大小是 。请你把 IP 地址转换成一个整数。(IPv4)
例如, 114.55.207.244 的二进制表示是 01110010 00110111 11001111 11110100 ,其十进制表示是 7590617063
"114.55.207.244"
"1916260340"
"0.0.0.1"
"1"
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param ip string字符串 * @return string字符串 */ public String IPtoNum(String ip) { // write code here String[] split = ip.split("\\."); StringBuilder sb = new StringBuilder(); for (int i = 0; i < split.length; i++) { String s = Integer.toBinaryString(Integer.parseInt(split[i])); // 如果不够位数,首尾补0 while (s.length() < 8) { s = "0" + s; } sb.append(s); } return String.valueOf(Long.parseLong(sb.toString(), 2)); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param ip string字符串 * @return string字符串 */ public String IPtoNum (String ip) { // write code here String[] strNum = ip.split("\\."); String strLevel = ""; for (String str : strNum){ String strLengthFill = Integer.toBinaryString(Integer.parseInt(str)); int J = 8 - strLengthFill.length(); for (int j = 0; j < (J) ; j++) strLengthFill = "0" + strLengthFill; strLevel = strLevel + strLengthFill; } return new BigInteger(strLevel, 2).toString(); } /* public static String IPtoNum (String ip) { // write code here StringBuilder strNum = new StringBuilder(""); StringBuilder strBblank = new StringBuilder(""); StringBuilder strB = new StringBuilder(ip); strB.append("."); BigInteger bigInt = new BigInteger("0",10); for ( int i = 0 ; i < strB.length() ; i++ ){ if (strB.charAt(i)!='.') { strBblank.append(strB.charAt(i)); }else{ bigInt = new BigInteger(strBblank.toString(), 10); String strLengthFill = bigInt.toString(2); int J = 8 - strLengthFill.length(); for (int j = 0; j < (J) ; j++) strLengthFill = "0" + strLengthFill; strNum.append(strLengthFill); strBblank = new StringBuilder(""); } } bigInt = new BigInteger(strNum.toString(), 2); return bigInt.toString(); }*/ }