This is not the shortest solution, but I believe straightforward solutions are more instructive.
Consider the binary representation of the number.
Every 0 at the ith position from the right. adds 2**i to the result.
def findComplement(self, N): binary = bin(N)[2:] ans = 0 for i, u in enumerate(binary[::-1]): if u == '0': ans += 2 ** i return ans