- 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
- 62 lines of C++ from the credited upstream file 751.cpp.
- 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:3 vector<string> ipToCIDR(string ip, int n) {4 vector<string> ans;5 long num = getNum(ip);6 7 while (n > 0) {8 const long lowbit = num & -num;9 const long count = lowbit == 0 ? maxLow(n) : firstFit(lowbit, n);10 ans.push_back(getCIDR(num, getPrefix(count)));11 n -= count;12 num += count;13 }14 15 return ans;16 }17 18 private:19 long getNum(const string& ip) {20 istringstream iss(ip);21 long num = 0;22 for (string token; getline(iss, token, '.');)23 num = num * 256 + stol(token);24 return num;25 }26 27 28 int maxLow(int n) {29 for (int i = 0; i < 32; ++i)30 if (1 << i + 1 > n)31 return 1 << i;32 throw;33 }34 35 long firstFit(long lowbit, long n) {36 while (lowbit > n)37 lowbit >>= 1;38 return lowbit;39 }40 41 string getCIDR(long num, long prefix) {42 const long d = num & 255;43 num >>= 8;44 const long c = num & 255;45 num >>= 8;46 const long b = num & 255;47 num >>= 8;48 const long a = num & 255;49 return to_string(a) + '.' + to_string(b) + '.' + to_string(c) + '.' +50 to_string(d) + '/' + to_string(prefix);51 }52 53 54 55 int getPrefix(long count) {56 for (int i = 0; i < 32; ++i)57 if (count == 1 << i)58 return 32 - i;59 throw;60 }61};62