<題目描述>
給定一個非負整數 num。對於 0 ≤ i ≤ num 範圍中的每個數字 i ,計算其二進制數中的 1 的數目並將它們作爲數組返回。
<原題鏈接>
https://leetcode-cn.com/problems/counting-bits/
<理明思路>
O(n)算法會在後續更新。
<樣例代碼>
#!/usr/bin/python3
class Solution:
def getbin(self, n):
bin_sum = 0
while n > 0:
bin_sum += n % 2
n //= 2
return bin_sum
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = []
for i in range(num + 1):
ans.append(self.getbin(i))
return ans