class Solution: def findComplement(self, n: int) -> int: if n == 0: return 1 mask = n # Create mask of length matching num of bits # in n (taken from Hacker's Delight, Figure 3-1) mask |= mask >> 1 # \ mask |= mask >> 2 # \ mask |= mask >> 4 # |> Totalling 31 bits mask |= mask >> 8 # / mask |= mask >> 16 # / # XOR 1 will flip the bit return n ^ mask