LeetCode-191. Number of 1 Bits

https://leetcode.com/problems/number-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.

Solution

思路:把一个整数减去1,再和原整数做与运算,会将该整数最右边的一个1变成0。那么一个整数有几个1,就可以对其做几次这样的操作。

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n:
            count += 1
            n = n & (n-1)
            
        return count
        
posted @ 2016-11-21 22:14  BinWone  阅读(104)  评论(0编辑  收藏  举报