Problem overview
HalvingSteps receives a positive int n and returns how many times you must divide it by 2 until it becomes 1. Each division is an integer division, so the remainder is dropped. For 8 the path is 8, 4, 2, 1: three divisions. For 9 it is 9, 4, 2, 1, also three, since 9 divided by 2 gives 4. For 1 no division is needed, so the answer is 0.
Approach
You don't know in advance how many divisions it takes, so a while loop fits better than a for loop. The loop keeps going while n is bigger than 1. Each pass divides n by 2 and counts one step. A separate counter, steps, remembers how many passes ran.
In C#, dividing two int values with / truncates, so 9 / 2 is 4 and not 4.5. That matches the lesson's rule that the remainder is dropped.
Step by step
- Create
stepsas anintset to 0. No division has happened yet. - Write
while (n > 1). Whennis 1 from the start, the loop doesn't run and the answer stays 0. - Divide
nby 2 and store the result back inn. It gets smaller on every pass, so it must reach 1. - Add 1 to
stepswith++. Each pass is one division. - Return
stepsafter the loop.
For n = 9:
| Pass | n after dividing | steps |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
Now n > 1 is false, so the loop ends and the method returns 3.
The solution in C#
class Solution {
public int HalvingSteps(int n) {
int steps = 0;
while (n > 1) {
n = n / 2;
steps++;
}
return steps;
}
}
The method changes its own copy of n, which is fine, because the caller's number is untouched.
Division in C#
The kind of division depends on the operand types, not on how you want the answer. With int a = 7, b = 2, a / b is 3, a % b is 1, and (double)a / b is 3.5. In this lesson both operands are integers, so you get the whole-number result for free, and the remainder is thrown away.
Written as a for loop, the same idea is for (; n > 1; n /= 2) steps++;. A while loop shows the three parts, the test, the division and the count, more clearly.
Two more checks on the answer: a power of two such as 8 gives exactly its exponent, 3, and the number just below the next power, such as 15, gives the same count as 8 because every division rounds down.
Complexity
Each pass halves n, so the loop runs about log base 2 of n times. That is the answer itself. For n = 1000000000, the largest allowed input, it is 29 passes. Memory use is constant: two integers.
Edge cases and common mistakes
n = 1. The loop is skipped and the answer is 0.- The wrong condition. With
while (n > 0), the loop would go on to 0 and count one step too many. - A missing division. If
nis never changed, the loop never ends. - Odd numbers. The remainder is dropped, so 9 goes to 4 and 5 goes to 2. Odd numbers need no special handling.
Testing
The solution returns 3 for 8, 3 for 9, 0 for 1 and 29 for 1000000000.
