[LeetCode]#338. Counting Bits
Jul 21, 2021
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:
- Use loop and n is loop end. Convert input number to binary such as 1 to ‘0b1’.
- Replace ‘ob’ with ‘’.
- Count all ‘1’ numbers.
- 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