Given a positive integer num, return the smallest positive integerxwhose multiplication of each digit equalsnum. If there is no answer or the answer is not fit in 32-bit signed integer, return 0.
To form the smallest number whose digits multiply to num, we factorize num using digits from 9 down to 2. We use the largest possible digits first to minimize the number of digits, then arrange them in increasing order to get the smallest integer.
classSolution {
public:int smallestFactorization(int num) {
if (num ==1) return1;
vector<int> ds;
for (int d =9; d >=2; --d) {
while (num % d ==0) {
ds.push_back(d);
num /= d;
}
}
if (num !=1) return0;
longlong ans =0;
sort(ds.begin(), ds.end());
for (int d : ds) {
ans = ans *10+ d;
}
return ans > INT_MAX ?0: (int)ans;
}
};
classSolution {
publicintsmallestFactorization(int num) {
if (num == 1) return 1;
List<Integer> ds =new ArrayList<>();
for (int d = 9; d >= 2; d--) {
while (num % d == 0) {
ds.add(d);
num /= d;
}
}
if (num != 1) return 0;
Collections.sort(ds);
long ans = 0;
for (int d : ds) {
ans = ans * 10 + d;
}
return ans > Integer.MAX_VALUE? 0 : (int)ans;
}
}
classSolution {
funsmallestFactorization(num: Int): Int {
if (num ==1) return1val ds = mutableListOf<Int>()
var n = num
for (d in9 downTo 2) {
while (n % d ==0) {
ds.add(d)
n /= d
}
}
if (n !=1) return0 ds.sort()
var ans = 0Lfor (d in ds) {
ans = ans * 10 + d
}
returnif (ans > Int.MAX_VALUE) 0else ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
defsmallest_factorization(num: int) -> int:
if num ==1:
return1 ds: list[int] = []
n = num
for d in range(9, 1, -1):
while n % d ==0:
ds.append(d)
n //= d
if n !=1:
return0 ds.sort()
ans =0for d in ds:
ans = ans *10+ d
return ans if ans <=2**31-1else0
impl Solution {
pubfnsmallest_factorization(num: i32) -> i32 {
if num ==1 { return1; }
letmut ds =vec![];
letmut n = num;
for d in (2..=9).rev() {
while n % d ==0 {
ds.push(d);
n /= d;
}
}
if n !=1 { return0; }
ds.sort();
letmut ans: i64=0;
for d in ds {
ans = ans *10+ d asi64;
}
if ans >i32::MAXasi64 { 0 } else { ans asi32 }
}
}