Problem overview
The function halvingSteps takes a positive Int, 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 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
The task describes a loop directly: keep dividing while the value is bigger than 1, and count how often you did it. The count is the answer. Nothing has to be computed in advance, and no formula is needed. The number of divisions grows slowly: 1000000000 needs only 29 of them, because each division halves what is left.
Step by step
- Copy
nintovar num. Scala parameters are read-only, like aval, so the loop needs a variable of its own. - Create
var steps, starting at 0. It counts the divisions. - Write a
whileloop with the conditionnum > 1. Ifnis already 1, the loop doesn't run and the answer stays 0. - Inside the loop, set
numtonum / 2. - Still inside the loop, add 1 to
stepswithsteps += 1. - After the loop, return
steps.
For n = 9 the loop runs three times:
| Turn | num after the turn | steps after the turn |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
Why the loop ends, and how fast
For any num above 1, num / 2 is smaller but still at least 1: 2 gives 1, 3 gives 1, 4 gives 2. So the value never skips past 1 to 0, and it strictly shrinks, which guarantees that the loop stops exactly at 1. The count is about the base-2 logarithm of n, rounded down: the number of times you can halve a value before it reaches 1. That is why a huge input like 1000000000 finishes after only 29 turns.
The solution in Scala
class Solution {
def halvingSteps(n: Int): Int = {
var num = n
var steps = 0
while (num > 1) {
num = num / 2
steps += 1
}
return steps
}
}
Details that matter in Scala:
varallows reassignment andvaldoesn't, so bothnumandstepsarevar./between twoIntvalues truncates, so9 / 2is 4. If you wrote2.0instead of2, the types would no longer matchnum, and the code wouldn't compile as it stands.- Scala has no
++for numbers, so the counter grows withsteps += 1. - The condition is
> 1, not> 0. The loop must stop when the value reaches 1.
Edge cases and common mistakes
- n equal to 1. The condition is false at once, and the function returns 0.
- Odd numbers. The remainder is dropped on every division. For 9 the sequence is 9, 4, 2, 1, and the count is 3, the same as for 8.
- Looping on
num > 0. After 1 the next division gives 0, which adds one extra step. The loop would count one division too many. - Forgetting the division. Without
num = num / 2the loop never ends for anynabove 1. - Counting the starting value. The count is the number of divisions, which is the number of arrows in the chain, not the number of values in it.
Testing
halvingSteps(8) -> 3
halvingSteps(9) -> 3
halvingSteps(1) -> 0
halvingSteps(1000000000) -> 29
