Intermedio 0 resueltos 0% de aceptación

Digital Root

Sum the digits repeatedly until one digit remains.

Lo que aprenderás

  • 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 traducción

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.

Restricciones

1 ≤ n ≤ 10¹⁸

Ejemplos

Ejemplo 1
Entrada:
n = 999

Salida esperada:
expected = 9
Entrada:
long long n = 999;

Salida esperada:
long long expected = 9;
Entrada:
long n = 999;

Salida esperada:
long expected = 9;

Explicación

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

Ejemplo 2
Entrada:
n = 38

Salida esperada:
expected = 2
Entrada:
long long n = 38;

Salida esperada:
long long expected = 2;
Entrada:
long n = 38;

Salida esperada:
long expected = 2;

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Adding digits repeatedly eventually collapses the number to one digit.

Pista 2

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

Pista 3

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

Complejidad esperada

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

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.