Условие
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
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. Следуйте условию и ограничениям выше.