minimum-number-of-steps-to-reduce-number-to-1 1

minimum-number-of-steps-to-reduce-number-to-1

#minimum-number-of-steps-to-reduce-number-to-1
def stepCount(n):
    count = 0
    while n > 1:
        if n % 2 == 0:             # bitmask: *0
            n = n // 2
        elif n == 3 or n % 4 == 1: # bitmask: 01
            n = n - 1
        else:                      # bitmask: 11
            n = n + 1
        count += 1
    return count

Here is what the above code is Doing:
1. If n is even, divide by 2.
2. If n is odd and not equal to 3, subtract by 1.
3. If n is odd and equal to 3, add by 1.
4. If n is 1, stop.

The above steps are guaranteed to terminate because every number n will either:
1. Be reduced to 1.
2. Be reduced to a number less than n.

The number of steps is clearly bounded by the value of n.

The above steps are also guaranteed to be the minimum number of steps, because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is odd and equal to 3, the steps are optimal.

The above steps are optimal because:
1. If n is even, the steps are optimal.
2. If n is odd and not equal to 3, the steps are optimal.
3. If n is

Similar Posts