Halving Total
Start from the non-negative integer n and repeatedly halve it with integer division (the remainder is dropped) until it becomes 0. Return the sum of every value seen along the way, counting n itself and not counting the final 0.
For example, n = 13 passes through 13, 6, 3 and 1, so the answer is 13 + 6 + 3 + 1 = 23. For n = 0 the answer is 0.
Example 1
n 13
returns 23
13 halves to 6, then 3, then 1, then 0; the values before 0 add up to 23.
Example 2
n 0
returns 0
Nothing is seen before the final 0.
Constraints
0 <= n <= 10**9
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Largest DigitBeginner
- Multiply It OutBeginner
- Nested SumBeginner
- Rising DigitsBeginner
- Ruler PatternBeginner
- Same Both WaysBeginner
- Suffix ChainBeginner
- Wheels in the RowBeginner