中級 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 つずつ開いてみましょう。

ヒント 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

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。