338. Counting Bits
Problem¶
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
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 –> 0
1 –> 1
2 –> 10
3 –> 11
4 –> 100
5 –> 101
Constraints:
0 <= n <= 10**5
Follow up:
- It is very easy to come up with a solution with a runtime of
O(n log n)
. Can you do it in linear timeO(n)
and possibly in a single pass? - Can you do it without using any built-in function (i.e., like
__builtin_popcount
in C++)?
Solve¶
Built-in bit_count()
python¶
O(n log n)
Python number have built-in bit_count()
that give us total 1
in bit representation of any number. We assuming this take log n
to count it.
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
09/01/2023 17:47 | Accepted | 65 ms | 23.2 MB | python3 |
class Solution:
def countBits(self, n: int) -> List[int]:
return [i.bit_count() for i in range(n+1)]
Dynamic programming¶
O(n)
We can split any binary number into <right-shift> + <remain 1/0>
, for example 100110111001
can be split into 10011011100
and 1
:
bit_count(100110111001) = bit_count(10011011100) + bit_count(1)
= bit_count(100110111001 >> 1) + bit_count(1)
Formula:
With this formula, we can create a simple Dynamic programing solution:
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
09/01/2023 19:45 | Accepted | 70 ms | 23 MB | python3 |
class Solution:
def countBits(self, n: int) -> List[int]:
cache = [0]
count = 0
for i in range(1,n+1):
cache.append(cache[(i >> 1)] + (i & 1))
return cache
Last update :
September 17, 2023
Created : September 3, 2023
Created : September 3, 2023