原题 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.

  1. 2149583361 ==> "128.32.10.1"
  2. 32 ==> "0.0.0.32"
  3. 0 ==> "0.0.0.0"

 

  1. public class Kata {
  2. public static String longToIP(long ip) {
  3. //1. translate the ip to binary representation
  4. String str = "";
  5. if (ip == 0) {
  6. str = ip + "";
  7. } else {
  8. while (ip != 0) {
  9. str = ip % 2 + str;
  10. ip = ip / 2;
  11. }
  12. }
  13. //2. if the binary string short than 32 bit, then add "0" in front
  14. while (str.length() != 32) {
  15. str = "0" + str;
  16. }
  17. String result = "";
  18. //3. truncate the str to four items
  19. for (int i = 0; i < 4; i++) {
  20. String partStr = str.substring(i * 8, 8 * (i + 1));
  21. //4. translate every item to decimal number
  22. int bi = Integer.parseInt(partStr, 2);
  23. if (i == 3) {
  24. result += bi + "";
  25. } else {
  26. result += bi + ".";
  27. }
  28. }
  29. return result;
  30. }
  31. }

 

1.

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

2.

  1. public class Kata {
  2. public static String longToIP(long ip) {
  3. String[] e = new String[4];
  4. int i = 4;
  5. while (i-- != 0) {
  6. e[i] = "" + (ip % 256);
  7. ip /= 256;
  8. }
  9. return String.join(".",e);
  10. }
  11. }

3.

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

 

版权声明:本文为ukzq原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/ukzq/p/11176910.html