Problema
Add up the digits of n. If the result has more than one digit, add up its digits again. Repeat until a single digit remains.
Implement digital_root(n).
Input
n: A positive integer.
Output
Return the final single digit.
Restrições
1 ≤ n ≤ 10¹⁸
Exemplos
Entrada:
n = 999
Saída esperada:
expected = 9
Entrada:
long long n = 999;
Saída esperada:
long long expected = 9;
Entrada:
long n = 999;
Saída esperada:
long expected = 9;
Explicação
9 + 9 + 9 = 27, then 2 + 7 = 9.
Entrada:
n = 38
Saída esperada:
expected = 2
Entrada:
long long n = 38;
Saída esperada:
long long expected = 2;
Entrada:
long n = 38;
Saída esperada:
long expected = 2;
Explicação
3 + 8 = 11, then 1 + 1 = 2.
Como abordar
Tente sozinho primeiro e depois abra uma dica de cada vez.
Dica 1
Adding digits repeatedly eventually collapses the number to one digit.
Dica 2
You can simulate the repeated summing process until the value is less than 10.
Dica 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
Complexidade esperada
O(d log n) time, O(1) extra space