class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
a =""
a = str(bin(n))[2:]# 将整数转化为二进制字符串
b =[int(char)forcharin a]# 将二进制字符串转换为整数列表
count =0foriin range(len(b)):
# 遍历列表if b[i]==1:
count +=1return count
时间复杂度: O(log(n)) ,因为n的二进制表示大约需要 log(n) 位
空间复杂度: O(log(n))
2. 位运算
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count =0while n:
count += n &1# 通过与运算判断最低位是否为1
n >>=1# 右移一位,继续检查下一个二进制位return count
时间复杂度: O(log(n))
空间复杂度: O(1)
3. 取余和整数除法
class Solution(object):
def hammingWeight(self, n):
a =0if n ==0:
return0while n >0:
a += n % 2# 判断最低位是否为1
n //=2# 将n右移一位return a