Number of 1 Bits

Problem: Number of 1 Bits

We can construct a number 000...001 (actually it's just one) and do AND operation on this number and the argument, if we can one, then its last bit is one. Then we move the argument's bits right 1 bit and do the same thing until there's only 0 left in the number, which means our argument becomes 0.

Code in Python:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n:
            if n & 1:
                count += 1
            n >>= 1
        return count

results matching ""

    No results matching ""