問題
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
例
入力:
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.
入力:
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用に調整されています。上記の説明と制約に従ってください。