[codewars] - int32 to IPv4 二进制十进制 ip地址转换

原题 https://www.codewars.com/kata/int32-to-ipv4/train/java

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"

 

solution : 

public class Kata {
    public static String longToIP(long ip) {
        //1. translate the ip to binary representation
        String str = "";
        if (ip == 0) {
            str = ip + "";
        } else {
            while (ip != 0) {
                str = ip % 2 + str;
                ip = ip / 2;
            }
        }

        //2. if the binary string short than 32 bit, then add "0" in front
        while (str.length() != 32) {
            str = "0" + str;
        }

        String result = "";
        //3. truncate the str to four items
        for (int i = 0; i < 4; i++) {
            String partStr = str.substring(i * 8, 8 * (i + 1));
            //4. translate every item to decimal number
            int bi = Integer.parseInt(partStr, 2);
            if (i == 3) {
                result += bi + "";
            } else {
                result += bi + ".";
            }
        }
        return result;
    }
}

 

CW上的大神解: 

1.

public class Kata {
  public static String longToIP(long ip) {
    return String.format("%d.%d.%d.%d", ip>>>24, (ip>>16)&0xff, (ip>>8)&0xff, ip&0xff);
  }
}

2.

public class Kata {
  public static String longToIP(long ip) {
    String[] e = new String[4];
    int i = 4;
    while (i-- != 0) {
      e[i] = "" + (ip % 256);
      ip /= 256;
    }
    return String.join(".",e);
  }
}

3.

public class Kata {
  public static String longToIP(long ip) {
    return IntStream.rangeClosed(1, 4)
      .mapToObj(i -> String.valueOf(ip >> (32 - 8 * i) & 255))
      .collect(Collectors.joining("."));
  }
}

 

posted @ 2019-07-12 16:35  ukyo--君君小时候  阅读(1047)  评论(0编辑  收藏  举报