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.
Vincoli
1 ≤ n ≤ 10¹⁸
Esempi
Input:
n = 999
Output atteso:
expected = 9
Input:
long long n = 999;
Output atteso:
long long expected = 9;
Input:
long n = 999;
Output atteso:
long expected = 9;
Spiegazione
9 + 9 + 9 = 27, then 2 + 7 = 9.
Input:
n = 38
Output atteso:
expected = 2
Input:
long long n = 38;
Output atteso:
long long expected = 2;
Input:
long n = 38;
Output atteso:
long expected = 2;
Spiegazione
3 + 8 = 11, then 1 + 1 = 2.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Adding digits repeatedly eventually collapses the number to one digit.
Suggerimento 2
You can simulate the repeated summing process until the value is less than 10.
Suggerimento 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
Complessità attesa
O(d log n) time, O(1) extra space