您的位置:首页 > 其它

leetcode--Number of 1 Bits

2016-02-29 16:14 351 查看
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.

解:

除了不断%2的解法之外,更有效率的是位操作,容易想到的解法是将num与不同的bit mask相&,得到每一位上的值,再相加,更elegant的方法是将num减一,

- 如果n最后一位是1,n-1则将最后一位置为0,n&(n-1) 将最后一位置0

- 如果n最后一位是0,n&n-1 将n从后往前第一个1置0

也就是n&=n-1 不断删除n为1的位

class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum=0
while n!=0:
n&=(n-1)
sum+=1
return sum
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: