import unittest

import utils


# O(1) time. O(1) space. Bit manipulation.
class Solution(object):
    def bitwiseComplement(self, N):
        """
        :type N: int
        :rtype: int
        """
        tmp = N
        shift = 0

        if tmp > 0xffff:
            tmp >>= 16
            shift += 16
        if tmp > 0xff:
            tmp >>= 8
            shift += 8
        if tmp > 0xf:
            tmp >>= 4
            shift += 4
        if tmp > 3:
            tmp >>= 2
            shift += 2
        if tmp > 1:
            tmp >>= 1
            shift += 1

        mask = (1 << (shift + 1)) - 1

        return (~N) & mask


class Test(unittest.TestCase):
    def test(self):
        cases = utils.load_test_json(__file__).test_cases

        for case in cases:
            actual = Solution().bitwiseComplement(**case.args._asdict())
            self.assertEqual(case.expected, actual)


if __name__ == '__main__':
    unittest.main()

@@ -248,15 +248,17 @@
 mp %3E
- 0xffff
+= 1 %3C%3C 16
 :%0A  
@@ -322,13 +322,16 @@
 mp %3E
- 0xff
+= 1 %3C%3C 8
 :%0A  
@@ -393,12 +393,16 @@
 mp %3E
- 0xf
+= 1 %3C%3C 4
 :%0A  
@@ -464,10 +464,16 @@
 mp %3E
- 3
+= 1 %3C%3C 2
 :%0A  
@@ -511,24 +511,24 @@
  shift += 2%0A
-
         if t
@@ -531,16 +531,22 @@
 if tmp %3E
+= 1 %3C%3C
  1:%0A    

Improve readability