Tous les défis
Facile 0 résolus 0 % de réussite

Disarium Number

Check whether a number equals the sum of its digits raised to their positions.

Ce que vous allez apprendre

  • Read digits from left to right
  • Raise a digit to its position with integer arithmetic
  • Add powers without overflow

Problème

Afficher la traduction

Number the digits of n from the left starting at 1, raise each digit to the power of its position, and add the results. If the total is n itself, the number is a disarium number. For example, 175 gives 1¹ + 7² + 5³ = 1 + 49 + 125 = 175.

Implement disarium_number(n).

Input

n: The number to test.

Output

Return true if n is a disarium number, otherwise false. Every single-digit number is a disarium number.

Contraintes

1 ≤ n ≤ 10^9

Exemples

Exemple 1
Entrée :
n = 89

Sortie attendue :
expected = True
Entrée :
long long n = 89;

Sortie attendue :
bool expected = true;
Entrée :
long n = 89;

Sortie attendue :
bool expected = true;

Explication

8¹ + 9² = 8 + 81 = 89, so the answer is true.

Exemple 2
Entrée :
n = 98

Sortie attendue :
expected = False
Entrée :
long long n = 98;

Sortie attendue :
bool expected = false;
Entrée :
long n = 98;

Sortie attendue :
bool expected = false;

Explication

9¹ + 8² = 9 + 64 = 73, not 98, so the answer is false.

Comment l'aborder

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

Indice 1

Positions count from the left, so either turn n into a string or count the digits first.

Indice 2

Use integer multiplication for powers instead of a floating point function.

Indice 3

The largest term is 9^10, which fits easily in 64 bits.

Complexité attendue

O(d^2) time for d digits, O(1) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

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