Problem overview
The function halvingSteps receives a positive integer n and returns how many times it must be divided by 2 to reach 1. Each division is an integer division that drops the remainder. For 8 the chain is 8, 4, 2, 1: three divisions. For 9 it is 9, 4, 2, 1, also three, because 9 divided by 2 gives 4. For 1 no division is needed, so the answer is 0.
Approach
Do exactly what the task says: keep dividing and keep counting. A while loop fits because you don't know in advance how many divisions it takes. The loop condition is "the number is still bigger than 1".
The values after each pass for 9:
| Pass | num after | steps after |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
The number halves each time, so it shrinks fast: even the largest input, 1000000000, needs only 29 divisions.
Step by step
- Copy
nintonumwithvar. A parameter can't be reassigned. - Start
stepsat 0 withvar, since it grows inside the loop. - Loop while
num > 1. Forn = 1the loop doesn't run and the answer stays 0. - Divide:
num = num / 2. - Count the division with
steps++. - Return
steps.
The solution in Kotlin
class Solution {
fun halvingSteps(n: Int): Int {
var num = n
var steps = 0
while (num > 1) {
num = num / 2
steps++
}
return steps
}
}
Some details worth knowing:
- Integer division. Both operands are
Int, so9 / 2is 4, not 4.5. That is the behaviour the task asks for. - Why the loop ends. For
num > 1,num / 2is smaller thannumand at least 1, so the value reaches 1 and stops. The conditionnum > 0would be a bug: from 1,1 / 2is 0, and the count would be one too high. - The answer is the floor of log base 2. The count equals the position of the highest 1 bit of
n. That is why 8 and 9 both give 3.
Why a loop is the right tool
The number of divisions depends on n, so the code can't be written as a fixed number of statements. A while loop with the condition from the task, "until it becomes 1", expresses that directly. The loop body does one division and one count, and the condition is checked again before the next pass.
It helps to read the loop as a contract. Before every check, steps is the number of divisions made so far and num is what is left. When num reaches 1, nothing is left to divide, and steps is the answer. Because the check comes first, a starting value of 1 ends the function with 0 divisions and no special case.
Complexity
Time is O(log n), since the number halves each pass. Space is O(1).
Edge cases and common mistakes
n = 1. No pass runs; the answer is 0.- Powers of 2.
8gives 3, an exact count.1000000000, which is not a power of 2, gives 29. - Looping to 0. Use
num > 1, notnum > 0. - Forgetting
steps++. The function would always return 0.
Testing
8gives3.9gives3.1gives0.1000000000gives29.
