簡単 0件解決済み 正答率0%

Spy Number

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

このチャレンジで学べること

  • 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

問題

翻訳を表示

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.

制約

1 ≤ n ≤ 10^18

例

例 1
入力:
n = 123

期待される出力:
expected = True
入力:
long long n = 123;

期待される出力:
bool expected = true;
入力:
long n = 123;

期待される出力:
bool expected = true;

解説

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

例 2
入力:
n = 1234

期待される出力:
expected = False
入力:
long long n = 1234;

期待される出力:
bool expected = false;
入力:
long n = 1234;

期待される出力:
bool expected = false;

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Walk over the digits once and update both totals.

ヒント 2

Start the product at 1, not 0.

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。