|
| 1 | +# Counting Bits |
| 2 | + |
| 3 | +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 |
| 4 | +in the binary representation of i. |
| 5 | + |
| 6 | +## Examples |
| 7 | + |
| 8 | +```text |
| 9 | +Example 1: |
| 10 | +
|
| 11 | +Input: n = 2 |
| 12 | +Output: [0,1,1] |
| 13 | +Explanation: |
| 14 | +0 --> 0 |
| 15 | +1 --> 1 |
| 16 | +2 --> 10 |
| 17 | +``` |
| 18 | + |
| 19 | +``` |
| 20 | +Example 2: |
| 21 | +
|
| 22 | +Input: n = 5 |
| 23 | +Output: [0,1,1,2,1,2] |
| 24 | +Explanation: |
| 25 | +0 --> 0 |
| 26 | +1 --> 1 |
| 27 | +2 --> 10 |
| 28 | +3 --> 11 |
| 29 | +4 --> 100 |
| 30 | +5 --> 101 |
| 31 | +``` |
| 32 | + |
| 33 | +## Constraints |
| 34 | + |
| 35 | +- 0 <= `n` <= 10^5 |
| 36 | + |
| 37 | +## Solution |
| 38 | + |
| 39 | +This solution uses a bottom-up dynamic programming approach to solve the problem. |
| 40 | +The key to this problem lies in the fact that any binary number can be broken down into two parts: the least-significant |
| 41 | +(rightmost bit), and the rest of the bits. The rest of the bits can be expressed as the binary number divided by 2 |
| 42 | +(rounded down), or `i >> 1`. |
| 43 | + |
| 44 | +For example: |
| 45 | +- 4 in binary = 100 |
| 46 | +- rightmost bit = 0 |
| 47 | +- rest of bits = 10, which is also (4 // 2) = 2 in binary. |
| 48 | + |
| 49 | +When the number is odd, |
| 50 | +- 5 in binary = 101 |
| 51 | +- rightmost bit = 1 |
| 52 | +- rest of bits = 10, which is also (5 // 2) = 2 in binary. |
| 53 | + |
| 54 | +in the binary representation of i is that number plus 1 if the rightmost bit is 1. We can tell if the last significant |
| 55 | +bit is 1 by checking if it is odd. |
| 56 | + |
| 57 | +As an example, we know that the number of 1's in 2 is 1. This information can be used to calculate the number of 1's in 4. |
| 58 | +The number of 1's in 4 is the number of 1's in 2 plus 0, because 4 is even. |
| 59 | + |
| 60 | +This establishes a recurrence relationship between the number of 1's in the binary representation of i and the number of |
| 61 | +1's in the binary representation of i // 2: if count[i] is the number of 1's in the binary representation of i, then |
| 62 | +count[i] = count[i // 2] + (i % 2). |
| 63 | + |
| 64 | +With the recurrence relationship established, we can now solve the problem using a bottom-up dynamic programming approach. |
| 65 | +We start with the base case dp[0] = 0, and then build up the solution for dp[i] for i from 1 to n. |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
0 commit comments