思路方法
三种思路的速度都很慢,不知道为什么,找不到高效率的算法
思路一
按照定义,将输入的数表示成二进制的字符串,数一下有多少个1即可。
代码
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1')
思路二
通过移位操作,一位一位的判定是否是数字1。
代码
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
count += n&1
n >>= 1
return count
思路三
利用 n&(n-1)
的trick。简单的说,运算 n = n&(n-1)
可以将n最低位的1变成0,这里不证明。循环进行该运算,循环次数就是n的二进制表示中1的个数。
代码
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
count += 1
n &= n-1
return count