链接
https://leetcode-cn.com/problems/counting-bits/
前言
不难,用bin()和count()函数秒解
题目
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
- 示例1
输入: 2
输出: [0,1,1]
示例 2:
输入: 5
输出: [0,1,1,2,1,2]
关键
遍历+统计
本人思路
- 遍历0到num的数字(for循环)
- 将遍历的数字转化为二进制数(bin函数),并计算二进制数每个位上有多少个1(count函数)
- 将计算得到的个数存在预设矩阵中(append函数)
- 遍历完成后输出矩阵(return)
class Solution:
def countBits(self, num: int) -> List[int]:
b = []
for i in range(num+1):
a = bin(i).count('1')
b.append(a)
return b
- 注意复杂度分析