Problem overview
The method CountBits receives an int n and returns an int[] of n + 1 numbers. Entry bits[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.
For n = 5 the numbers 0 to 5 are 0, 1, 10, 11, 100, 101 in binary, so the answer is [0,1,1,2,1,2]. For n = 0 the only number is 0, which has no 1 bits, so the answer is [0].
Approach: reuse a smaller answer
You could count the bits of every number on its own, which takes up to about 17 steps per number for n up to 100,000. The lesson does better by noticing that the numbers share work.
Shifting a number right by one place drops its last bit. 13 is 1101, and 13 shifted right is 110, which is 6. So 13 has the 1 bits of 6, plus its own last bit. That last bit is i & 1: 1 for an odd number and 0 for an even one.
In a formula, bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i, its count is already in the array when you fill the array from 1 upward. Every number costs one step, so the whole job is O(n).
Step by step
- Create
bitsasnew int[n + 1]. The array holdsn + 1numbers because 0 is included. C# fills a newintarray with zeros, andbits[0]is 0 anyway, as 0 has no 1 bits. - Loop
ifrom 1 up toninclusive (i <= n). Counting upward is essential: each number reads the entry of a smaller one, which must already be filled. - Set
bits[i] = bits[i >> 1] + (i & 1). Keep the parentheses aroundi & 1: in C#,+binds tighter than&, so without them the expression would add first and AND afterwards. - Return
bits.
Here is the array for n = 13:
[0,1,1,2,1,2,2,3,1,2,2,3,2,3]
Entry 13 is bits[6] + (13 & 1), which is 2 + 1 = 3, matching 1101.
The solution in C#
class Solution {
public int[] CountBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}
Details worth knowing:
- Array size and last index. An array of length
n + 1has valid indices 0 ton, sobits[n]is valid. Reading or writing beyond it throwsIndexOutOfRangeException. >>on anintis an arithmetic shift, which keeps the sign for negative numbers. Hereiis never negative, so it simply halvesiand rounds down:i >> 1equalsi / 2for non-negative values.i & 1is anint. It is 0 or 1, so it adds to the other count directly with no cast.
Complexity
Time: O(n). The loop does one lookup, one shift, one AND and one addition per number. Space: O(1) besides the returned array, which has to exist anyway: only the loop variable i is extra.
Edge cases and common mistakes
n = 0. The loop doesn't run and the result is[0], an array of one element.- Size
ninstead ofn + 1. The last write,bits[n], would throw anIndexOutOfRangeException. - Stopping at
i < n. The last entry would stay 0 and be wrong. - Missing parentheses.
bits[i >> 1] + i & 1adds first, then ANDs the sum with 1, giving only 0 or 1 for every entry. - Looping downward. The entry for
i >> 1would still be 0 when it's needed.
Testing
n = 2gives[0,1,1].n = 5gives[0,1,1,2,1,2].n = 0gives[0].n = 13gives[0,1,1,2,1,2,2,3,1,2,2,3,2,3].
