Star

LeetCode Weekly Contest 625. Minimum Factorization

Question

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:

48 Output: 68 Example 2 Input:

15 Output: 35

Explanation

很直接的解法,从9开始找因子,存起来,最后组成最小的数。

Code

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
32
33
34
35
36
37
public class Solution {
public int smallestFactorization(int a) {
if(a == 0) return 0;
ArrayList<Integer> list = new ArrayList<>();
helper(a, list);
if (list.get(0) == 0) return 0;
int result = 0;
for (int i=list.size()-1; i>=0; i--) {
int digit = i;
result += list.get(i) * Math.pow(10,digit);
if (result >= Integer.MAX_VALUE) {
return 0;
}
}
return result;
}
public void helper(int a, ArrayList<Integer> list) {
if (a <= 9) {
list.add(a);
return;
}
boolean could = false;
for (int i = 9; i>=2; i--) {
if (a%i == 0) {
could = true;
list.add(i);
helper(a/i, list);
break;
}
}
if(!could) {
if (list.size() <1) list.add(0);
else list.set(0,0);
}
}
}