Number complement python solution


  • 0
    A
    class Solution(object):
        def findComplement(self, num):
            """
            :type num: int
            :rtype: int
            """
            if not num: return 1  # To handle zero
            if num==0x7fffffff: return 0 # To handle (1<<31)-1
            numDigs = int(math.ceil(math.log(1+num)/math.log(2))) #   num of digits in binary number
            ones = int(numDigs*'1',2) # Create a mask of 1's equal to # of digits
            return num^ones 
    

Log in to reply
 

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