Médio 0 resolvidos 0% de aceitação

Digital Root

Sum the digits repeatedly until one digit remains.

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

1 ≤ n ≤ 10¹⁸

Exemplos

Exemplo 1
Entrada:
n = 999

Saída esperada:
expected = 9
Entrada:
long long n = 999;

Saída esperada:
long long expected = 9;
Entrada:
long n = 999;

Saída esperada:
long expected = 9;

Explicação

9 + 9 + 9 = 27, then 2 + 7 = 9.

Exemplo 2
Entrada:
n = 38

Saída esperada:
expected = 2
Entrada:
long long n = 38;

Saída esperada:
long long expected = 2;
Entrada:
long n = 38;

Saída esperada:
long expected = 2;

Explicação

3 + 8 = 11, then 1 + 1 = 2.

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

Adding digits repeatedly eventually collapses the number to one digit.

Dica 2

You can simulate the repeated summing process until the value is less than 10.

Dica 3

Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.

Complexidade esperada

O(d log n) time, O(1) extra space

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.