Facile 0 résolus 0 % de réussite

Spy Number

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

Ce que vous allez apprendre

  • 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

Problème

Afficher la traduction

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.

Contraintes

1 ≤ n ≤ 10^18

Exemples

Exemple 1
Entrée :
n = 123

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

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

Sortie attendue :
bool expected = true;

Explication

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

Exemple 2
Entrée :
n = 1234

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

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

Sortie attendue :
bool expected = false;

Explication

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

Comment l'aborder

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

Indice 1

Walk over the digits once and update both totals.

Indice 2

Start the product at 1, not 0.

Indice 3

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

Complexité attendue

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