748. Digital Root (Recursive Digit Sum)

EasyRecursionRecursion

Given a non-negative integer n, repeatedly sum its digits until a single digit remains, and return that single digit. This final value is called the digital root of n.

Solve it using recursion: sum the digits once, then recurse on the result until it is a single digit.

Input: A single non-negative integer n.

Output: A single integer (0-9) — the digital root of n.

Examples

Example 1
Input: 12345
Output: 6
Explanation: 1+2+3+4+5=15 → 1+5=6.
Example 2
Input: 0
Output: 0
Explanation: Already a single digit.
Example 3
Input: 99999
Output: 9
Explanation: Sum=45 → 4+5=9.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →