문제
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.
제약 조건
1 ≤ n ≤ 10¹⁸
예시
입력:
n = 999
예상 출력:
expected = 9
입력:
long long n = 999;
예상 출력:
long long expected = 9;
입력:
long n = 999;
예상 출력:
long expected = 9;
설명
9 + 9 + 9 = 27, then 2 + 7 = 9.
입력:
n = 38
예상 출력:
expected = 2
입력:
long long n = 38;
예상 출력:
long long expected = 2;
입력:
long n = 38;
예상 출력:
long expected = 2;
설명
3 + 8 = 11, then 1 + 1 = 2.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Adding digits repeatedly eventually collapses the number to one digit.
힌트 2
You can simulate the repeated summing process until the value is less than 10.
힌트 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
예상 복잡도
O(d log n) time, O(1) extra space