LeetCode Solutions

625. Minimum Factorization

Time: $O(8\log \texttt{a}) = O(\log \texttt{a})$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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