题目:
Given a positive integer a
, find the smallest positive integer b
whose multiplication of each digit equals to a
.
If there is no answer or the answer is not fit in 32-bit signed integer, then return 0.
Example 1
Input:
48Output:
68
Example 2
Input:
15Output:
35
思路:
可以观察到两个事实:1)n位数一定小于n+1位的数;2)如果几个结果都是n位数,那么将各个位上的数按照升序排列,则形成的n位数结果是最小的。所以我们的思路就是尽量让结果的位数小,并且让因数从大到小。所以可以让i从9循环到2,按照顺序找出a中所有9-2之间的因数(注意不是质因数),然后将它们按照升序排列,形成的结果即为题目所求。我们这里让d < 10是为了防止int溢出。
代码:
class Solution {
public:
int smallestFactorization(int a) {
if (a < 2) {
return a;
}
long l = 0;
for (int i = 9, d = 0; i >= 2 && d < 10; --i) {
while (a % i == 0 && d < 10) {
l += i * pow(10, d++);
a /= i;
}
}
return a > 1 || l > INT_MAX ? 0 : l;
}
};