Digit multiplier

Given a positive integer N, find the smallest number S such that the product of all the digits of S is equal to the number N.

Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains a positive integer N.

Output: Print out the number S. If there exists no such number, then print -1.

Constraints: 1 <= T <= 200 1 <= N <= 109

Examples: Input: 2 100 26 Output: 455 -1

class Solution {
    // 1st prefernce is reducing the digits
    // 2nd prefernce is forming min digit among same digits set
    public long minDigit(int n) {
        if(n==1)
            return 1;
        // For getting minimum number of digits
        // We take bigger factors first(9 8 7 ...2)
        // Double digits factors will be covered by single digits
        List<Integer> digits = new ArrayList<>();
        int factor = 9;
        // 1st Prefernce
        while (n > 1 && factor > 1) {
            while (n % factor == 0) {
                n = n / factor;
                digits.add(factor);
            }
            factor--;
        }
        // Edge case -> PrimeNumber
        if (n != 1)
            return -1;
        // 2nd prefernce
        // Now our list contains digits in decreasing order
        // Min ans will be reverse of this
        long ans = 0;
        for (int i = digits.size() - 1; i >= 0; i--)
            ans = ans * 10 + digits.get(i);
        return ans;
    }
}

Last updated