Problem overview
The function halvingSteps receives a positive integer n, up to 1,000,000,000, and returns how many times it must be divided by 2 until it becomes 1. Every division is an integer division, so the remainder is dropped: 9 divided by 2 gives 4. If n is already 1, no division is needed and the answer is 0.
For n = 8 the chain is 8, 4, 2, 1: three divisions. For n = 9 it is 9, 4, 2, 1, also three, because 9 / 2 drops the remainder 1 and gives 4.
Approach
This is a counting loop. While n is bigger than 1, halve it and count one step. The loop stops as soon as n is 1, so the counter holds every division made on the way.
The loop always ends, because for any n greater than 1, n / 2 is smaller than n and at least 1. It can't skip past 1 to 0: the smallest value that enters the loop is 2, and 2 / 2 is 1.
Here is the loop on n = 9, with the state after each pass:
n=4 steps=1
n=2 steps=2
n=1 steps=3
Step by step
- Create
stepsas anintstarting at 0. No division has been made yet. - Start a
whileloop with the conditionn > 1. Ifnis 1 from the start, the loop doesn't run and the answer stays 0. - Replace
nwithn / 2. The remainder is dropped, so 9 becomes 4. - Add 1 to
stepswith++. Each pass is one division. - Return
stepsafter the loop.
The solution in C++
class Solution {
public:
int halvingSteps(int n) {
int steps = 0;
while (n > 1) {
n = n / 2;
steps++;
}
return steps;
}
};
Notes:
- Integer division. With two
intoperands,/keeps only the whole part. Writingn / 2.0would produce adouble, and storing it back in anintwould truncate it again, so the whole-number division is the clearer choice. - The answer is the number of bits minus one. The count equals the position of the highest 1 bit of
n. The function returns 3 for both 8 and 9, 1 for 2 and 3, and 29 for 1000000000, so even the largest input needs only 29 passes. nis a copy. The parameter is passed by value, so the caller's variable isn't changed.
Complexity
Time: O(log n). The value halves on every pass, so the loop runs about log base 2 of n times. Space: O(1).
Edge cases and common mistakes
n = 1. The loop condition is false, so the answer is 0.- Odd numbers. The dropped remainder doesn't add a step: 9 needs three divisions, the same as 8.
- Using
n >= 1. The loop would then run once more withnequal to 1, making it 0, so every answer would be one too high. - Leaving a line outside the braces. The order of
n = n / 2andsteps++inside the loop doesn't matter, but both must be inside it. Ifsteps++sits after the closing brace, it runs once and the answer is always 1.
Testing
n = 8gives 3.n = 9gives 3.n = 1gives 0.n = 2gives 1.n = 3gives 1.n = 1000000000gives 29.
