मध्यम 0 हल किए गए 0% स्वीकृति

Digital Root

Sum the digits repeatedly until one digit remains.

आप क्या सीखेंगे

  • Sum digits repeatedly until one digit remains
  • Combine an inner loop with an outer stopping condition
  • Spot the shortcut formula with modulo 9

समस्या

अनुवाद दिखाएँ

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¹⁸

उदाहरण

उदाहरण 1
इनपुट:
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.

उदाहरण 2
इनपुट:
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

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।