Tutte le sfide
Facile 0 risolte 0% di accettazione

Disarium Number

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

1 ≤ n ≤ 10^9

Esempi

Esempio 1
Input:
n = 89

Output atteso:
expected = True
Input:
long long n = 89;

Output atteso:
bool expected = true;
Input:
long n = 89;

Output atteso:
bool expected = true;

Spiegazione

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

Esempio 2
Input:
n = 98

Output atteso:
expected = False
Input:
long long n = 98;

Output atteso:
bool expected = false;
Input:
long n = 98;

Output atteso:
bool expected = false;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.