समस्या
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