Problème
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.
Contraintes
1 ≤ n ≤ 10¹⁸
Exemples
Entrée :
n = 999
Sortie attendue :
expected = 9
Entrée :
long long n = 999;
Sortie attendue :
long long expected = 9;
Entrée :
long n = 999;
Sortie attendue :
long expected = 9;
Explication
9 + 9 + 9 = 27, then 2 + 7 = 9.
Entrée :
n = 38
Sortie attendue :
expected = 2
Entrée :
long long n = 38;
Sortie attendue :
long long expected = 2;
Entrée :
long n = 38;
Sortie attendue :
long expected = 2;
Explication
3 + 8 = 11, then 1 + 1 = 2.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Adding digits repeatedly eventually collapses the number to one digit.
Indice 2
You can simulate the repeated summing process until the value is less than 10.
Indice 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
Complexité attendue
O(d log n) time, O(1) extra space