- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 68 lines of Java from the credited upstream file 751.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> ipToCIDR(String ip, int n) {3 List<String> ans = new ArrayList<>();4 long num = getNum(ip.split("\\."));5 6 while (n > 0) {7 final long lowbit = num & -num;8 final long count = lowbit == 0 ? maxLow(n) : firstFit(lowbit, n);9 ans.add(getCIDR(num, getPrefix(count)));10 n -= (int) count;11 num += count;12 }13 14 return ans;15 }16 17 private long getNum(String[] x) {18 long num = 0;19 for (int i = 0; i < 4; ++i)20 num = num * 256 + Long.parseLong(x[i]);21 return num;22 }23 24 25 private int maxLow(int n) {26 for (int i = 0; i < 32; ++i)27 if (1 << i + 1 > n)28 return 1 << i;29 throw new IllegalArgumentException();30 }31 32 private long firstFit(long lowbit, long n) {33 while (lowbit > n)34 lowbit >>= 1;35 return lowbit;36 }37 38 private String getCIDR(long num, long prefix) {39 final long d = num & 255;40 num >>= 8;41 final long c = num & 255;42 num >>= 8;43 final long b = num & 255;44 num >>= 8;45 final long a = num & 255;46 return new StringBuilder()47 .append(a)48 .append(".")49 .append(b)50 .append(".")51 .append(c)52 .append(".")53 .append(d)54 .append("/")55 .append(prefix)56 .toString();57 }58 59 60 61 private int getPrefix(long count) {62 for (int i = 0; i < 32; ++i)63 if (count == 1 << i)64 return 32 - i;65 throw new IllegalArgumentException();66 }67}68