問題
A strong number is a number that equals the sum of the factorials of its digits. For example, 145 is strong because 1! + 4! + 5! = 1 + 24 + 120 = 145. Mathematicians call these numbers *factorions*; in base 10 there are only four of them, but your program should test the definition rather than a list.
Implement strong_number(n).
Use this definition: take each decimal digit d of n, add up d! for all of them (with 0! = 1), and compare the total with n. So 0 is not strong, because 0! = 1.
Input
n: The number to test.
Output
Return true if the sum of the factorials of the digits of n equals n, otherwise false.
制約
0 ≤ n ≤ 10^9
例
入力:
n = 145
期待される出力:
expected = True
入力:
long long n = 145;
期待される出力:
bool expected = true;
入力:
long n = 145;
期待される出力:
bool expected = true;
解説
1! + 4! + 5! = 1 + 24 + 120 = 145, which is the number itself, so the answer is true.
入力:
n = 123
期待される出力:
expected = False
入力:
long long n = 123;
期待される出力:
bool expected = false;
入力:
long n = 123;
期待される出力:
bool expected = false;
解説
1! + 2! + 3! = 1 + 2 + 6 = 9, and 9 ≠ 123, so the answer is false.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
Keep a copy of n, because you will change the working value while taking digits off.
ヒント 2
Only the factorials of 0 to 9 are ever needed, so build them once.
ヒント 3
Check what your loop does when n is 0: it has one digit.
目安の計算量
O(d) time for d digits, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。