Средне Решено: 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

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.