Facile 0 risolte 0% di accettazione

Spy Number

Check whether the sum of a number's digits equals the product of its digits.

Cosa imparerai

  • Track a sum and a product in one pass
  • Start a product at 1 and a sum at 0
  • Notice how a 0 digit affects the product

Problema

Mostra traduzione

A spy number is a positive integer whose digit sum equals its digit product. For example, 1124 has sum 1 + 1 + 2 + 4 = 8 and product 1 × 1 × 2 × 4 = 8, so it is a spy number.

Implement spy_number(n).

Input

n: The number to test.

Output

Return true if the sum of the decimal digits of n equals their product, otherwise false. Every single-digit number is a spy number.

Vincoli

1 ≤ n ≤ 10^18

Esempi

Esempio 1
Input:
n = 123

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

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

Output atteso:
bool expected = true;

Spiegazione

Sum 1 + 2 + 3 = 6 and product 1 × 2 × 3 = 6 are equal, so the answer is true.

Esempio 2
Input:
n = 1234

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

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

Output atteso:
bool expected = false;

Spiegazione

Sum 1 + 2 + 3 + 4 = 10 but product 1 × 2 × 3 × 4 = 24, so the answer is false.

Come affrontarlo

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

Suggerimento 1

Walk over the digits once and update both totals.

Suggerimento 2

Start the product at 1, not 0.

Suggerimento 3

Any number containing a 0 digit has product 0, so it cannot be spy unless the sum is 0 too.

Complessità attesa

O(d) 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.