3848. Check Digitorial Permutation
Description
You are given an integer n.
A number is called digitorial if the sum of the factorials of its digits is equal to the number itself.
Determine whether any permutation of n (including the original order) forms a digitorial number.
Return true if such a permutation exists, otherwise return false.
Note:
- The factorial of a non-negative integer
x, denoted asx!, is the product of all positive integers less than or equal tox, and0! = 1. - A permutation is a rearrangement of all the digits of a number that does not start with zero. Any arrangement starting with zero is invalid.
Β
Example 1:
Input: n = 145
Output: true
Explanation:
The number 145 itself is digitorial since 1! + 4! + 5! = 1 + 24 + 120 = 145. Thus, the answer is true.
Example 2:
Input: n = 10
Output: false
Explanation:βββββββ
10 is not digitorial since 1! + 0! = 2 is not equal to 10, and the permutation "01" is invalid because it starts with zero.
Β
Constraints:
1 <= n <= 109
Solutions
Solution 1: Simulation
According to the problem description, no matter how the digits of number \(n\) are rearranged, the sum of factorials of the digitorial number remains unchanged. Therefore, we only need to calculate the sum of factorials of each digit of number \(n\), and check whether the permutation of digits of this sum equals the permutation of digits of \(n\).
The time complexity is \(O(\log n)\), where \(n\) is the integer given in the problem. The space complexity is \(O(d)\), where \(d = 10\) is the length of the factorial preprocessing array.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |