Moyen 0 résolus 0 % de réussite

Digital Root

Sum the digits repeatedly until one digit remains.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

1 ≤ n ≤ 10¹⁸

Exemples

Exemple 1
Entrée :
n = 999

Sortie attendue :
expected = 9
Entrée :
long long n = 999;

Sortie attendue :
long long expected = 9;
Entrée :
long n = 999;

Sortie attendue :
long expected = 9;

Explication

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

Exemple 2
Entrée :
n = 38

Sortie attendue :
expected = 2
Entrée :
long long n = 38;

Sortie attendue :
long long expected = 2;
Entrée :
long n = 38;

Sortie attendue :
long expected = 2;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Adding digits repeatedly eventually collapses the number to one digit.

Indice 2

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

Indice 3

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

Complexité attendue

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

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.