Counting Bits
Bit ManipulationDynamic Programming
Problem Statement
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
Example 1:
Input: n = 2
Output: [0,1,1]
Solution (Dynamic Programming)
This problem can be solved efficiently using dynamic programming. The key insight is that the number of '1's in the binary representation of a number i
is related to the number of '1's in a smaller number.
Algorithm Steps
- Create an array
ans
of sizen + 1
. - Initialize
ans[0] = 0
. - For each number
i
from 1 ton
, the number of '1's isans[i >> 1] + (i & 1)
.
ans array
0
0
1
0
2
0
3
0
4
0
5
0
Start: Initialize an array 'ans' of size n+1 with zeros.
Counting Bits Solution