Problem overview
The method halvingSteps receives a positive integer n up to one billion and returns how many times it has to be divided by 2 before it becomes 1. Each division is an integer division, so the remainder is dropped: 9 divided by 2 gives 4.
For n = 8 the path is 8, 4, 2, 1, which is 3 divisions. For n = 9 it is 9, 4, 2, 1, again 3 divisions. For n = 1 nothing needs dividing, so the answer is 0.
Approach: loop until the value reaches 1
The number of steps isn't known in advance, so a while loop fits: keep halving while n is bigger than 1, and count each halving. Every pass shrinks n, so it must reach 1 and the loop ends. The count is about the base-2 logarithm of n, which is why even the largest input needs only a few dozen passes.
Step by step
- Create
stepsas anintstarting at 0. - Write
while (n > 1). Forn = 1the loop doesn't run, and the answer stays 0. - Divide
nby 2 and store the result back inn. - Add 1 to
stepswithsteps++, one for each division. - Return
stepsafter the loop.
The solution in Java
class Solution {
public int halvingSteps(int n) {
int steps = 0;
while (n > 1) {
n = n / 2;
steps++;
}
return steps;
}
}
Tracing n = 9: after the first pass n is 4 and steps is 1, then 2 and 2, then 1 and 3. The loop ends and the method returns 3. The largest allowed input, 1000000000, takes 29 passes.
Java details:
- Integer division.
9 / 2is 4 because both operands areint. With adoubleoperand it would be 4.5, and the loop would behave differently. - Odd numbers. Dropping the remainder just rounds down, so odd and even numbers need no separate handling.
- No overflow. The value only gets smaller. Even
2147483647, the largestint, takes 30 passes.
Another way: count the bits
Dividing by 2 and dropping the remainder removes the lowest bit of the number, so the loop counts the bits after the leading one. Java exposes that count: 31 - Integer.numberOfLeadingZeros(n) is the same value for every positive int. It gives 29 for 1000000000. The loop is easier to read and doesn't need any knowledge of bits.
Tracing 8 and 9
For n = 8 the pairs of n and steps after each pass are (4, 1), (2, 2) and (1, 3). For n = 9 they are (4, 1), (2, 2) and (1, 3) as well: the first division turns 9 into 4, and from there it follows the same path as 8. Both answers are 3.
Edge cases and common mistakes
- Starting at 1. The answer is 0 and the loop is skipped.
- Using
while (n > 0). The loop would divide 1 once more, giving 0, and return one too many. - Using
while (n != 1). This works for the allowed inputs, but a 0 would loop forever, since 0 / 2 is 0. The conditionn > 1is safer. - Forgetting to update
n. Writingn / 2without assigning the result changes nothing. - Counting steps without dividing. Both lines must be inside the loop.
Testing
8gives3.9gives3.1gives0.1000000000gives29.
