JonnyF--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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

解题思路

     这个问题其实就是将输入的数字先转换成二进制,然后求这个32位二进制中有几个“1”,因此我们可以先将这个数字转换成二进制,然后再求里面“1”的个数,就如下面代码中写的那样:

class Solution:
    # @param n, an integer
    # @return an integer
    def hammingWeight(self, n):
        return str(bin(n)).count('1')

      这是使用Python内置的方法bin()将这个十进制的数字转换成二进制的,然后再通过count()方法来求得其中的个数,虽然这很简单,但是效率却不是最好的,因此就有了如下的第二种方式,这种方式是将这个数字按位右移,如果出现了1那么就使总数增加,这样最后输出总数sum便可以知道结果了。

class Solution:
    # @param n, an integer
    # @return an integer
    def hammingWeight(self, n):
        sum = 0
        while(n!=0):
            sum += n&1
            n = n >> 1
        return sum
posted @ 2015-05-11 17:47  F-happy  阅读(95)  评论(0)    收藏  举报