Problem overview
The function halving_steps takes a positive n, at most 1_000_000_000, and returns how many times it must be divided by 2 to reach 1. Every division is an integer division, so the remainder is dropped and 9 divided by 2 is 4.
For n = 8 the path is 8, 4, 2, 1: three divisions. For n = 9 it is 9, 4, 2, 1: also three. For n = 1 no division is needed, so the answer is 0.
Approach
This is a counting loop. While the number is bigger than 1, halve it and add 1 to a counter. When the loop stops, the number is 1, and the counter holds every division made on the way.
For n = 9, the state after each pass is:
| pass | num after the pass | steps after the pass |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
The loop always ends, because num / 2 is smaller than num for every num above 1. The number of passes is about the base-2 logarithm of n: even the largest input, 1_000_000_000, needs only 29.
Step by step
- Copy
nintonumwithlet mut. Onlymutvariables can change, and parameters aren't. - Create
stepsat 0. It is mutable and counts the divisions. - Loop while
num > 1. Forn = 1the loop doesn't run and the answer stays 0. - Replace
numwithnum / 2. The integer division drops the remainder. - Add 1 to
stepswith+= 1: each pass is one division. - Return
stepsas the last expression.
The solution in Rust
impl Solution {
fn halving_steps(n: i32) -> i32 {
let mut num = n;
let mut steps = 0;
while num > 1 {
num = num / 2;
steps += 1;
}
steps
}
}
- Integer division. With both sides integers,
/truncates toward zero. For the positive numbers here that means dropping the fraction:9 / 2is 4. With floating-point numbers,9.0 / 2.0would be 4.5 and the loop would behave differently. - Inferred type.
stepsstarts as0and becomes ani32, because the function returns it. - Loop condition.
num > 1needs no parentheses in Rust, and the braces are required.
A pattern in the answers
Because each pass halves the number, every value from 8 to 15 needs three passes, and 16 needs four. The answer is the position of the highest set bit of n, which is why it grows so slowly: doubling the input adds one step. The loop doesn't need that insight, but it explains why even a billion needs only 29.
Rounding down also explains why odd numbers need no extra work. Going from 9 to 4 loses the remainder, and the loop simply carries on from 4.
Edge cases and common mistakes
- Already 1.
n = 1gives 0. - Not a power of two.
9and8both give 3. Every value from 8 to 15 gives 3, because each one halves down to 1 in the same number of passes. - The condition
num > 0. Since1 / 2is 0, it would take one extra pass after reaching 1, and the answer would be one too high. - Dividing
stepsinstead ofnum. The loop would never end, becausenumwould stay above 1.
Testing
n = 8gives 3.n = 9gives 3.n = 1gives 0.n = 2gives 1.n = 3gives 1.n = 1000000000gives 29.
