191.位1的个数
1.题目
2.我的解决方案
直接统计
class Solution:
def hammingWeight(self, n: int) -> int:
s = bin(n) # 读入是十进制,还是需要转换成二进制
return s.count('1')
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)
固定公式法
class Solution:
def hammingWeight(self, n: int) -> int:
# 使用x&(x-1)的固定公式,能消去x最右边的1
# 统计能消多少次即可
res = 0
while n > 0:
n = n & (n-1)
res += 1
return res
- 时间复杂度: O ( l o g n ) O(logn) O(logn)
- 空间复杂度: O ( n ) O(n) O(n)