One Line Python code

  • 0

    In a complement, we need to reverse the 1s to 0s and 0s to 1s. One of the best ways to do it is to xor the number with all 1s. 2**len(bin(num).lstrip('0b'))-1 gives the integer value of all 1s greater than the given number.
    Here is the sample code.

    class Solution(object):
        def findComplement(self, num):
            :type num: int
            :rtype: int
            return num^(2**len(bin(num).lstrip('0b'))-1)

Log in to reply

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