[LeetCode]#338. Counting Bits

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
  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.
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store