Đề bài
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.
Ràng buộc
1 ≤ n ≤ 10¹⁸
Ví dụ
Đầu vào:
n = 999
Kết quả mong đợi:
expected = 9
Đầu vào:
long long n = 999;
Kết quả mong đợi:
long long expected = 9;
Đầu vào:
long n = 999;
Kết quả mong đợi:
long expected = 9;
Giải thích
9 + 9 + 9 = 27, then 2 + 7 = 9.
Đầu vào:
n = 38
Kết quả mong đợi:
expected = 2
Đầu vào:
long long n = 38;
Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long n = 38;
Kết quả mong đợi:
long expected = 2;
Giải thích
3 + 8 = 11, then 1 + 1 = 2.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Adding digits repeatedly eventually collapses the number to one digit.
Gợi ý 2
You can simulate the repeated summing process until the value is less than 10.
Gợi ý 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
Độ phức tạp mong đợi
O(d log n) time, O(1) extra space