- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of Python from the credited upstream file 751.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 def ipToCIDR(self, ip: str, n: int) -> list[str]:3 ans = []4 num = self._getNum(ip.split('.'))5 6 while n > 0:7 lowbit = num & -num8 count = self._maxLow(n) if lowbit == 0 else self._firstFit(lowbit, n)9 ans.append(self._getCIDR(num, self._getPrefix(count)))10 n -= count11 num += count12 13 return ans14 15 def _getNum(self, x: list[str]) -> int:16 num = 017 for i in range(4):18 num = num * 256 + int(x[i])19 return num20 21 def _maxLow(self, n: int) -> int | None:22 """Returns the maximum i s.t. 2^i < n."""23 for i in range(32):24 if 1 << i + 1 > n:25 return 1 << i26 27 def _firstFit(self, lowbit: int, n: int) -> int:28 while lowbit > n:29 lowbit >>= 130 return lowbit31 32 def _getCIDR(self, num: int, prefix: int) -> str:33 d = num & 25534 num >>= 835 c = num & 25536 num >>= 837 b = num & 25538 num >>= 839 a = num & 25540 return '.'.join([str(s) for s in [a, b, c, d]]) + '/' + str(prefix)41 42 def _getPrefix(self, count: int) -> int | None:43 """44 e.g. count = 8 = 2^3 . prefix = 32 - 3 = 2945 count = 1 = 2^0 . prefix = 32 - 0 = 3246 """47 for i in range(32):48 if count == 1 << i:49 return 32 - i50