题解 | #IP地址转化#
IP地址转化
http://www.nowcoder.com/practice/67ae7c321ae147049ad569c8fe5c98cd
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param ip string字符串
* @return string字符串
*/
public String IPtoNum(String ip) {
// write code here
StringBuffer sb = new StringBuffer("");
String[] strs = ip.split("\\.");
for (String str : strs) {
sb.append(DecimalToBinary(Integer.valueOf(str)));
}
String tmpStr = new String(sb);
char[] chrs = tmpStr.toCharArray();
long ans = 0l;
int account = 0;
for (int i = chrs.length - 1; i > -1; i--) {
if (Integer.valueOf(chrs[i] + "") == 1) {
ans += ((long) Math.pow(2, account));
}
account++;
}
return String.valueOf(ans);
}
public String DecimalToBinary(int num) {
StringBuffer sb = new StringBuffer("");
while (0 != num) {
sb.append(num % 2);
num /= 2;
}
sb.reverse();
String ans = new String(sb);
while (ans.length() != 8) {
ans = "0" + ans;
}
return ans;
}
}