要求
给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例 1:
输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
核心代码
class Solution:
def countBits(self, n: int) -> List[int]:
res = list()
for i in range(n+1):
res.append(self.getOnes(i))
return res
def getOnes(self,n):
binary = list()
while n>=2:
binary.append(n % 2)
n = n// 2
binary.append(n)
return sum(binary)
另一思路:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = list()
for i in range(num + 1):
res.append(self.getOne(i))
return res
def getOne(self, n):
cnt = 0
while(n):
cnt += 1
n = n & (n - 1)
return cnt
第三思路
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0 for i in range(num + 1)]
for i in range(1, num + 1):
dp[i] = dp[i & (i - 1)] + 1
return dp
解题思路:第一种思路:线性扫描,我们直接使用对2取余的方法,将十进制的数变成2进制,最后通过sum加和的方式我们就能得到数字i种含有的1的个数,我们对0~n进行循环,得到每一个数字的种1的个数,最后得到我们想要的结果。第二种思路和第三种思路暂时记住。