Leetcode 191. Number of 1 Bits
题目描述:统计二进制中1的位数。
初步想法就是沿用上题190的思路,右移n,然后不断按位与操作来进行计数。
当然也可以用我以前面试的时候答的转成字符串哈哈哈~
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
while(n):
if((n&1)==1):
ans += 1
n >>= 1
return ans
参考链接
191. Number of 1 Bits | 汉明重量几种解法