Write a function that accepts a starting and ending IPv4 address, and returns the number of IP addresses from start
to end
, excluding the end
IP address.
All input to the ipsBetween
function will be valid IPv4 addresses in the form of strings. The end
ing address will be at least one address higher than the start
ing address.
Examples:ipsBetween("10.0.0.0", "10.0.0.50")
=> returns 50 ipsBetween("10.0.0.0", "10.0.1.0")
=> returns 256 ipsBetween("20.0.0.10", "20.0.1.0")
=> returns 246
大意:嗯就是算IP地址的差
复习一下IP是什么呢,这里也不扯太深入的(我才不会说自己也搞不懂呢)
网络之间互连的协议(IP)是Internet Protocol的缩写,中文简称网协(摘自百度百科)
然后呢IP地址就是给每个连接在互联网上的主机分配的一个32位地址,划重点,32位就是32个二进制位,那么问题的解法就来了
IP地址转换为32二进制位,然后相减取十进制差
附上代码:
import java.text.DecimalFormat;
public class CountIPAddresses {
public static long ipsBetween(String start, String end) {
DecimalFormat df = new DecimalFormat("00000000");
StringBuilder startBinary = new StringBuilder();
StringBuilder endBinary = new StringBuilder();
String[] strartArr = start.split("\\u002E");
String[] endArr = end.split("\\u002E");
for (String s : strartArr){
startBinary.append(df.format(Integer.valueOf(Integer.toBinaryString(Integer.parseInt(s)))));
}
for (String s : endArr){
endBinary.append(df.format(Integer.valueOf(Integer.toBinaryString(Integer.parseInt(s)))));
}
return Long.valueOf(endBinary.toString(),2) - Long.valueOf(startBinary.toString(),2);
}
}
PS:. 符号需要转义