Skip to content
BytePatterns

Halve or Subtract One Steps

EasyRecursion#tail-recursion#bit-counting~15m

Problem

Start from a whole number n that is zero or more. In one step, halve it if it is even, or subtract one if it is odd. Return how many steps it takes to reach zero. The number can be as large as 2 to the power 1000, so a solution that makes one recursive call per step will run past Python's default recursion limit.

Examples

Input:  n = 14
Output: 6
Why:    14 -> 7 -> 6 -> 3 -> 2 -> 1 -> 0
Input:  n = 2 ** 1000
Output: 1001
Why:    1000 halvings reach 1, and one subtraction reaches 0
Input:  n = 0
Output: 0
Why:    edge case, already at zero, so no steps are taken

Hints

0 / 3

Stuck on the idea rather than the code? Tail Calls and Loops covers it.