Đề bài
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.
Ràng buộc
0 ≤ n ≤ 10^9
Ví dụ
Đầu vào:
n = 145
Kết quả mong đợi:
expected = True
Đầu vào:
long long n = 145;
Kết quả mong đợi:
bool expected = true;
Đầu vào:
long n = 145;
Kết quả mong đợi:
bool expected = true;
Giải thích
1! + 4! + 5! = 1 + 24 + 120 = 145, which is the number itself, so the answer is true.
Đầu vào:
n = 123
Kết quả mong đợi:
expected = False
Đầu vào:
long long n = 123;
Kết quả mong đợi:
bool expected = false;
Đầu vào:
long n = 123;
Kết quả mong đợi:
bool expected = false;
Giải thích
1! + 2! + 3! = 1 + 2 + 6 = 9, and 9 ≠ 123, so the answer is false.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Keep a copy of n, because you will change the working value while taking digits off.
Gợi ý 2
Only the factorials of 0 to 9 are ever needed, so build them once.
Gợi ý 3
Check what your loop does when n is 0: it has one digit.
Độ phức tạp mong đợi
O(d) time for d digits, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.