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. Every division is an integer division: the remainder is dropped, so 9 divided by 2 is 4.
For n = 8 the values are 8, 4, 2, 1, which is three divisions. For n = 9 they are 9, 4, 2, 1, again three. For n = 1 nothing has to be done, so the answer is 0.
Approach
Keep a counter and a loop. While n is bigger than 1, halve it and add one to the counter. When n reaches 1 the loop ends, and the counter holds the number of divisions made.
In TypeScript, 9 / 2 is 4.5: the / operator divides doubles and does not drop anything. To get the integer division the task describes, round down with Math.floor. For positive numbers Math.trunc gives the same result.
The trace for 9:
| Turn | n after halving | steps |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
The loop stops because n is now 1, and the function returns 3.
Step by step
- Declare
stepswithletas anumber, starting at 0. It counts the divisions and grows in the loop, so it isn't aconst. - Write a
whileloop with the conditionn > 1. Ifnis 1 from the start, the loop doesn't run and the answer stays 0. - Halve
nwithn = Math.floor(n / 2). - Count it with
steps++. Each turn is exactly one division. - Return
stepsafter the loop.
The solution in TypeScript
class Solution {
halvingSteps(n: number): number {
let steps: number = 0;
while (n > 1) {
n = Math.floor(n / 2);
steps++;
}
return steps;
}
}
steps++is a statement here. It adds 1 tosteps. Its value is not used.- The loop always ends. For
nat least 2,Math.floor(n / 2)is smaller thannand still at least 1, sonshrinks until it is 1 and never skips past it. - Types are labels.
numberis erased when TypeScript compiles to JavaScript, and it doesn't makenan integer. TheMath.floorcall is what keeps it whole.
Complexity
Time: O(log n). Each turn halves n, so the number of turns is about log2(n). The largest allowed input, 1000000000, returns 29.
Space: O(1). Only steps and n are kept.
Edge cases and common mistakes
n = 1. No turn happens and the function returns 0.n = 2andn = 3. Both give 1: 2 becomes 1, and 3 becomes 1 because 3 / 2 is 1.5, rounded down.- Dropping
Math.floor. 9 / 2 would stay 4.5, then 2.25, 1.125, 0.5625. The conditionn > 1would still fail at 0.5625, but the count would be 4 instead of 3, so the answer would be wrong. - Looping while
n > 0. The task stops at 1, not at 0. This adds an extra step. - Counting before the loop condition fails. Adding 1 at the end, outside the loop, gives an answer one too high.
Testing
n = 8gives3.n = 9gives3.n = 1gives0.n = 2gives1.n = 3gives1.n = 1000000000gives29.
