Straightforward Python

  • 2

    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

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.