GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-2/java/751_IP_to_CIDR.java at master · ning609/leetcode-2 Expand file tree/ Copy path751_IP_to_CIDR.javaMore file actions 34 lines (34 loc) · 989 Bytes / Copy path751_IP_to_CIDR.javaFile metadata and controls34 lines (34 loc) · 989 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public List<String> ipToCIDR(String ip, int n) { long start = ipToLong(ip); List<String> ans = new ArrayList(); while (n > 0) { int mask = Math.max(33 - bitLength(Long.lowestOneBit(start)), 33 - bitLength(n)); ans.add(longToIP(start) + "/" + mask); start += 1 << (32 - mask); n -= 1 << (32 - mask); } return ans; } private long ipToLong(String ip) { long ans = 0; for (String x: ip.split("\\.")) { ans = 256 * ans + Integer.valueOf(x); } return ans; } private String longToIP(long x) { return String.format("%s.%s.%s.%s", x >> 24, (x >> 16) % 256, (x >> 8) % 256, x % 256); } private int bitLength(long x) { if (x == 0) return 1; int ans = 0; while (x > 0) { x >>= 1; ans++; } return ans; } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |