题目描述:
给你一个整数 n
,对于 0 <= i <= n
中的每个 i
,计算其二进制表示中 1
的个数 ,返回一个长度为 n + 1
的数组 ans
作为答案。
思路一:将每个数的二进制看成字符串,遍历每个字符串,统计"1"的个数
class Solution:
def countBits(self, n):
res = []
for i in range(0,n+1):
cnt = 0
s = str(bin(i))
for c in s:
if c == '1':
cnt += 1
res.append(cnt)
return res
思路二:位运算
class Solution:
def countBits(self, n):
bits = [0]*(n+1)
bits[0] = 0
for i in range(1,n+1):
if i & 1 == 1: # 如果为奇数
bits[i] = bits[i - 1] + 1 # 1的个数等于前一位的偶数1的个数加一
else: # 如果为偶数
bits[i] = bits[i>>1] # 1的个数等于这个数的1/2的1的个数
# 如 8(1000)>>1 = 4(100)
return bits
执行时间有了显著改善。