Python Bit - Manipulation Solution with Explanation


  • 1
    Z

    To test if an integer n has 1 in its binary representation, try n & (1<<digit). If the result is not 0, then that digit has 1. For example, integer 2 ('10' in binary ). 2 & (1<<0) = 2 & 1 = '10' & '01' = 0, so 0th digit doesn't have '1'. 2 & (1<<1) = 2 & 2 = '10' &'10' = 2, so 1st digit has '1'.

    def hammingWeight(self, n):
        res = 0 
        # Ex. bin(2) = '0b10'. We don't need first two digit 
        for i in range(len(bin(n))-2):
            # test if ith digit has '1'
            if n & (1<<i): 
                res += 1 
        return res

Log in to reply
 

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