Problem overview
The function 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, so the remainder is dropped. For n = 8 the path is 8, 4, 2, 1 and the answer is 3. For n = 9 it is 9, 4, 2, 1, because 9 divided by 2 gives 4, and the answer is again 3. If n is already 1, nothing is divided and the answer is 0.
Approach
The number of repetitions isn't known in advance, which makes this a job for a while loop rather than a for loop. Keep a counter, divide n by 2 while it is bigger than 1, and add one to the counter on each pass. When n reaches 1 the loop stops, and the counter holds the answer.
The loop condition n > 1 handles the case of n = 1 on its own: the test fails at once, the body never runs, and the counter stays 0.
Step by step
- Start
stepsat 0. No division has been made yet. - Loop while
n > 1. At 1 the goal is reached, so the loop stops there. - Set
nton // 2. The value gets smaller on every pass, so the loop is sure to end. - Add 1 to
steps. Each pass of the loop is one division. - Return
stepsafter the loop.
On n = 9 the loop runs like this:
| Pass | n after dividing | steps |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
Now n is 1, the condition n > 1 is false, and the function returns 3.
The solution in Python
class Solution:
def halvingSteps(self, n: int) -> int:
steps = 0
while n > 1:
n = n // 2
steps += 1
return steps
Details worth knowing:
//against/.9 // 2is 4, but9 / 2is the float 4.5. With/the value would go 9, 4.5, 2.25, and so on, and it would never be exactly 1, so the counting would be wrong.- Floor division and odd numbers.
//rounds down, so odd numbers lose their extra 1:3 // 2is 1. That is why 9 and 8 take the same number of steps. - The answer grows slowly. Halving shrinks the number very fast. For
n = 1000000000the function returns only 29. - The loop variable is the parameter. The function changes its own copy of
n. The caller's number isn't affected.
Edge cases and common mistakes
- n equals 1. The answer is 0, with no special case needed.
- n equals 2 or 3. Both take one step: 2 // 2 and 3 // 2 are both 1.
- Using
n > 0. The loop would divide 1 once more, to 0, and the answer would be one too large. For 8 it would count 4. - Forgetting to store the result. Writing
n // 2alone computes a value and throws it away, sonnever shrinks and the loop never ends.
Testing
8gives3.9gives3.1gives0.2gives1.3gives1.1000000000gives29.
