Problem overview
The function count_bits receives an integer n and returns a vector of n + 1 numbers. Entry 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 answer is [0].
Approach: reuse the answer for a smaller number
Counting the bits of each number separately works, but it costs up to about 17 steps per number for n up to 100,000. The lesson wants a constant amount of work per number, so each answer has to come from one that is already known.
Shifting a number right by one place drops its last bit. The number 13 is 1101, and 13 >> 1 is 110, which is 6. So 13 has the 1 bits of 6 plus its own last bit. In general:
bits[i] = bits[i >> 1] + (i & 1)
The value i >> 1 is smaller than i for every i of at least 1, so filling the vector from left to right guarantees that its entry is already there. And i & 1 is 1 for odd numbers and 0 for even ones. For n = 13 the loop produces [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3]: the last entry is bits[6] + 1 = 2 + 1 = 3.
Step by step
- Create
bitswithn + 1zeros. The size isn as usize + 1, because vector sizes areusize. The entry for 0 is already correct. - Loop
ifrom 1 up tobits.len(). The range1..bits.len()stops before the length, so the lastiisn. Going upward matters: each entry needs the one fori >> 1to be filled in first. - Apply the formula. Take the stored count for
i >> 1and add the last bit ofi. - Return
bitsas the last expression, without a semicolon.
The solution in Rust
impl Solution {
fn count_bits(n: i32) -> Vec<i32> {
let mut bits = vec![0i32; n as usize + 1];
for i in 1..bits.len() {
bits[i] = bits[i >> 1] + (i & 1) as i32;
}
bits
}
}
Rust details worth knowing:
- Types. The loop variable
iis ausize, because it indexes the vector, soi >> 1andi & 1areusizevalues too. The counts stored inbitsarei32, so the last bit needsas i32before it can be added. Rust never adds two different integer types silently. - Parentheses.
(i & 1) as i32converts the result of the AND. Without the parentheses,i & 1 as i32would cast only the1, and the AND of ausizewith ani32would not compile. vec![0i32; n as usize + 1]. The suffix0i32fixes the element type, which matches the return typeVec<i32>. The castn as usizecomes before the+ 1, becauseasbinds tighter than+.- Indexing is checked. Reading
bits[i >> 1]is always inside the vector here. An index out of range would panic, never read memory it shouldn't.
Complexity
Time: O(n). The loop runs n times, and each pass does a shift, an AND, an addition and a store.
Space: O(1) extra. Apart from the vector that the function returns, only the loop variable is kept.
Edge cases and common mistakes
n = 0. The vector has one entry,[0], and the range1..1is empty, so the loop doesn't run.- Off by one on the size. The answer needs
n + 1entries, because 0 is included. A vector ofnentries would panic when the loop reaches the last index. - Looping the wrong way. Going from
ndown to 1 would read entries that are still 0. - Mixing types.
bits[i >> 1] + (i & 1)withoutas i32is a compile error, because ani32and ausizecan't be added. - Forgetting the last bit. Using only
bits[i >> 1]counts the bits of the shifted number and misses odd numbers' last 1.
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].
