Count of 1 bits

题目描述

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

chanllenge

if number n has m 1 bits, can you do it in O(m)

解题方法

shift and count 1 ones

最简单的方法,check每一个Bit是否是1,不断地shift到下一个bit 这样就要检查每一个bit, O(logn)

bitwise操作,直接每次找到一个1bits

这个具体操作过程是这样的,当我们从一个integer里减去1的时候,会将从右往左的所有0变成1,将最右边的1变为0

比如

110100, 减去1,变为110011, 这时候我们再对这两个数做一个&, 变为110000

所以每次的n & (n-1)可以将n的最后一个1 bit消去,用while判断是否已经消去所有的1

Solution

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

        return result

Reference