[LeetCode]#338. Counting Bits

Environment: Python 3.8

Key technique: bin, append, replace

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

Example 1:

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Analysis:

  1. Use loop and n is loop end. Convert input number to binary such as 1 to ‘0b1’.
  2. Replace ‘ob’ with ‘’.
  3. Count all ‘1’ numbers.
  4. Add them to the list.

Solution:

class Solution:
def countBits(self, n):
ans=[]
for i in range(n+1):
temp=bin(i).replace('ob', '')
ans.append(temp.count('1'))

return ans

Submissions:

Reference:

https://leetcode.com/problems/counting-bits/discuss/1348058/python