编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
官方解法:
解法一:库函数
class Solution(object):
def hammingWeight(self, n):
return bin(n).count("1")
解法二: 右移 32 次
class Solution:
def hammingWeight(self, n: int) -> int:
ret = sum(1 for i in range(32) if n & (1 << i))
return ret
class Solution(object):
def hammingWeight(self, n):
res = 0
while n:
res += n & 1 # 使用 n & 1 得到二进制末尾是否为 1
n >>= 1 # 把 n 右移 1 位,直至结束。
return res
解法三:消除二进制末尾的 1
详解:https://leetcode-cn.com/problems/number-of-1-bits/solution/fu-xue-ming-zhu-xiang-jie-wei-yun-suan-f-ci7i/
class Solution(object):
def hammingWeight(self, n):
res = 0
while n:
res += 1
n &= n - 1
return res
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn1m0i/