Clear Python solution using XOR


  • 0
    P
    class Solution(object):
        def findComplement(self, num):
            mask = 1
            while num > mask:
                mask = mask << 1 | 1
            return mask ^ num
    

    For example,

    num          = 00000101
    mask         = 00000111
    mask ^ num   = 00000010
    

Log in to reply
 

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