Digital Root

Easy · rating 850 · Math

Read an integer n. Repeatedly replace it with the sum of its digits until a single digit remains, and print that digit.

For example, 942 → 15 → 6.

Constraints: 0 ≤ n ≤ 109

Editorial

Approach

You can simulate the digit-summing, but there's a one-line shortcut. The digital root of a positive integer equals 1 + (n − 1) mod 9 — a consequence of the fact that a number is congruent to its digit sum modulo 9. Zero is a special case and maps to 0.

return 0 if n == 0 else 1 + (n - 1) % 9

Complexity

Time: O(1). Space: O(1).

Related problems

Open Digital Root in Code Arena →