Python easy to understand solution (Bit Manipulation).


  • 0
    C
    def hammingWeight1(self, n):
        res = 0
        for i in xrange(32):
            # res += (n & 1 << i != 0)
            res += (n >> i & 1)
        return res
        
    def hammingWeight(self, n):
        res = 0
        while n:
            res += n&1
            n /= 2
        return res

  • 1
    Y
    class Solution(object):    
        def hammingWeight(self, n):
            count = 0
            while n:
                count = count + n % 2
                n = n // 2
            return count

Log in to reply
 

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