forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_625.java
65 lines (55 loc) · 1.71 KB
/
_625.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 625. Minimum Factorization
*
* 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
*/
public class _625 {
public static class Solution1 {
/**
* reference: https://discuss.leetcode.com/topic/92854/java-solution-result-array
* and https://leetcode.com/articles/minimum-factorization/#approach-3-using-factorizationaccepted
*/
public int smallestFactorization(int a) {
//case 1: a < 10
if (a < 10) {
return a;
}
//case 2: start with 9 and try every possible digit
List<Integer> resultArray = new ArrayList<>();
for (int i = 9; i > 1; i--) {
//if current digit divides a, then store all occurences of current digit in res
while (a % i == 0) {
a = a / i;
resultArray.add(i);
}
}
//if a could not be broken in form of digits, return 0
if (a != 0) {
return 0;
}
//get the result from the result array in reverse order
long result = 0;
for (int i = resultArray.size() - 1; i >= 0; i--) {
result = result * 10 + resultArray.get(i);
if (result > Integer.MAX_VALUE) {
return 0;
}
}
return (int) result;
}
}
}