Problem overview
The function halvingSteps receives a positive integer n and returns how many times you have to divide it by 2 until it becomes 1. Each division is an integer division, so the remainder is dropped. For n = 8 the values go 8, 4, 2, 1, which is 3 divisions. For n = 9 they go 9, 4, 2, 1, because 9 divided by 2 gives 4, so the answer is 3 again. If n is already 1, no division is needed and the answer is 0.
Approach
Keep a working value and a counter. While the value is bigger than 1, halve it and add one to the counter. The loop condition is num > 1, so when n is 1 from the start, the loop doesn't run and the counter stays 0.
The number of steps grows slowly with n. For n = 1000000000 the answer is only 29, so even the largest input needs 29 passes through the loop. Each pass cuts the value roughly in half, so the number of passes grows like the number of binary digits of n, not like n itself.
Step by step
- Copy
nintovar num. Parameters are constants in Swift, so the loop needs its own variable. - Create
var steps = 0to count divisions. It is avarbecause it grows inside the loop. - Loop while
num > 1. - Replace
numwithnum / 2.Int / Intdrops the remainder, so 9 becomes 4. Sincenumgets smaller on every pass, it reaches 1 and the loop ends. - Add 1 to
stepswith+= 1. Each pass is one division. - Return
steps.
The solution in Swift
class Solution {
func halvingSteps(_ n: Int) -> Int {
var num = n
var steps = 0
while num > 1 {
num = num / 2
steps += 1
}
return steps
}
}
Swift details worth knowing:
- Integer division truncates toward zero.
7 / 2is 3, and for negative numbers-7 / 2is -3. This lesson only has positive values, so it behaves like rounding down. - Use
+= 1. Swift has no++. - Why the loop stops. For any value of 2 or more,
num / 2is at least 1 and strictly smaller thannum, sonumcan't skip past 1 or stay the same.
The answer is the position of the highest set bit of n: for 8 that is 3, and for 9 it is also 3. It is the largest k with two to the power k at most n, which is why 8 and 9 give the same answer and 16 gives 4.
Edge cases and common mistakes
n = 1. The loop is skipped and the answer is 0.- Small values.
2gives 1 and3gives 1, since 3 / 2 is 1. - Using
num >= 1in the loop. The value 1 would be divided once more, giving 0, and the answer would be one too high. - Dividing
ndirectly. It's a constant, so the code doesn't compile. - Expecting a fraction. With
Int, 9 / 2 is 4, not 4.5.
Testing
8gives 3.9gives 3.1gives 0.2gives 1.3gives 1.1000000000gives 29.
