此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 338. Counting Bits

解題思路

將每個數字轉換成binary(string)後在數每個字串裡總共有幾個一

我滴程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:

def counts(self, word:str) -> int:
count = 0
for ch in word:
if ch == "1":
count = count + 1
return count

def countBits(self, n: int) -> List[int]:
ans = []
for i in range(n+1):
ans.append(self.counts(str("{0:b}".format(i))))
return ans