Problem overview
The method halvingSteps receives a positive integer n and returns how many times it must be divided by 2 before it becomes 1. Each division is an integer division, so the remainder is dropped: 9 divided by 2 gives 4. For n = 8 the chain is 8, 4, 2, 1, which is three divisions. For n = 9 it is 9, 4, 2, 1, also three. For n = 1, no division is needed and the answer is 0.
Approach: loop until the value reaches 1
You don't know in advance how many divisions you'll need, so a while loop fits: keep halving while n is bigger than 1, and add 1 to a counter each time. The loop stops by itself the moment n is 1, and the counter holds the answer.
JavaScript's / is not an integer division. It keeps the fraction, so 9 / 2 is 4.5. Wrapping the result in Math.floor rounds it down to the whole number the lesson wants: Math.floor(9 / 2) is 4.
Step by step
- Declare
stepswithlet, starting at 0. It counts the divisions, and it changes inside the loop. - Loop while
n > 1. Whennis 1 from the start, the loop doesn't run and the answer stays 0. - Halve
n:n = Math.floor(n / 2). Every pass makesnsmaller, so it must reach 1 and the loop must end. - Add 1 to
stepswith++. One pass is one division. - Return
stepsafter the loop.
The solution in JavaScript
class Solution {
halvingSteps(n) {
let steps = 0;
while (n > 1) {
n = Math.floor(n / 2);
steps++;
}
return steps;
}
}
For halvingSteps(9), the values after each pass are:
| Pass | n | steps |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
After the third pass n is 1, so the loop ends and the method returns 3.
- The loop condition is
n > 1, notn > 0. The task stops at 1. Looping whilen > 0would do one extra division, from 1 to 0, and return one too many. - Floor and the odd numbers. For an odd number, halving rounds down: 9 gives 4, 5 gives 2 and 3 gives 1. Every number from 2 up gets strictly smaller, so the loop can't get stuck.
Edge cases and common mistakes
- One.
halvingSteps(1)returns 0. - Two and three.
halvingSteps(2)andhalvingSteps(3)both return 1: 2 becomes 1, and 3 becomes 1 after rounding down. - Powers of two against numbers just above them. 8 and 9 both need 3 divisions, and 16 needs 4. The answer grows by one each time
nreaches the next power of 2. - The largest input.
halvingSteps(1000000000)returns 29, so even the biggest value needs only a few dozen passes. Each pass halves what is left, so the number of passes grows very slowly asngrows. - Skipping
Math.floor. Without it,nbecomes 4.5, then 2.25, then 1.125, then 0.5625. The loop passes 1 without stopping on it and ends only whennis no longer above 1, so the count is too high. - Forgetting
steps++. The loop would still end, but the method would return 0 every time.
Testing
n = 8gives3.n = 9gives3.n = 1gives0.n = 2gives1.n = 1000000000gives29.
