题意
题目链接:https://www.codewars.com/kata/int32-to-ipv4/train/java/5cebc1b2c6c7fc0022674279
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
1st octet 128 has the binary representation: 10000000
2nd octet 32 has the binary representation: 00100000
3rd octet 10 has the binary representation: 00001010
4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: 2149583361
Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address.
Examples
2149583361 ==> "128.32.10.1"
32 ==> "0.0.0.32"
0 ==> "0.0.0.0"
题目意思是将一个长整型的的数字转换成ipv4,比如2149583361的二进制表示是10000000001000000000101000000001,而ipv4是每个点是之间的数值大小取值是0~255,也就是二进制的八位,因此将二进制表示按八位分一次是10000000.00100000.00001010.00000001,分好之后再将四组二进制重新转成十进制,算法的要点是十进制和二进制相互之间的转换,因为是刷算法题,我尽量去避免使用现有的一些Java库,手写转换的转换过程,这个没什么难度。我这里转换成二进制的过程是将二进制的每一位存入栈中,因为存在0.0.1.32、1.2.3.4等一些可能前面几组二进制的位数不能确定的情况,需要从后面开始每八位算一组来计算得出最后的ipv4地址,用栈会方便一些
代码
import java.util.Stack;
public class Kata {
public static String longToIP(long ip) {
// Java doesn't have uint32, so here we use long to represent int32
StringBuilder stringBuilder = new StringBuilder();
Stack<Integer> stack = new Stack<>();
while (ip > 0){
stack.push((int) (ip % 2));
ip /= 2;
}
while (stack.size() < 32){
stack.push(0);
}
int flag = 0;
int tmp = 0;
while (!stack.empty()){
tmp = tmp * 2 + stack.pop();
flag++;
if (flag % 8 == 0){
stringBuilder.append(tmp);
if (flag < 32){
stringBuilder.append('.');
}
tmp = 0;
}
}
return stringBuilder.toString(); // do it!
}
}
测试用例
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertEquals;
public class KataTest {
@Test
public void sampleTest() {
assertEquals("128.114.17.104", Kata.longToIP(2154959208L));
assertEquals("0.0.0.0", Kata.longToIP(0));
assertEquals("128.32.10.1", Kata.longToIP(2149583361L));
}
}