Skip to content

625. Minimum Factorization

  • Time: $O(8\log\texttt{num}) = O(\log\texttt{num})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int smallestFactorization(int num) {
    if (num == 1)
      return 1;

    long ans = 0;
    long base = 1;

    for (int i = 9; i > 1; --i)
      while (num % i == 0) {
        num /= i;
        ans = base * i + ans;
        base *= 10;
      }

    return num == 1 && ans <= INT_MAX ? ans : 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int smallestFactorization(int num) {
    if (num == 1)
      return 1;

    long ans = 0;
    long base = 1;

    for (int i = 9; i > 1; --i)
      while (num % i == 0) {
        num /= i;
        ans = base * i + ans;
        base *= 10;
      }

    return num == 1 && ans <= Integer.MAX_VALUE ? (int) ans : 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def smallestFactorization(self, num: int) -> int:
    if num == 1:
      return 1

    ans = 0
    base = 1

    for i in range(9, 1, -1):
      while num % i == 0:
        num //= i
        ans = base * i + ans
        base *= 10

    return ans if num == 1 and ans < 2**31 - 1 else 0