My java code (Math)?


  • 4
    M

    This problem is a little bit tricky. Factors should be selected from 2 to 9 and should be as large as possible.

    Any 10 digit solution will overflow.

    public int smallestFactorization(int a) {
        int k = 9;
        List<Integer> ans = new ArrayList<>();
        if (a <= 9) return a;
        while (a > 1 && k >= 2) {
            if (a % k == 0){
                ans.add(k);
                a = a / k;
            }
            else{
                k--;
            }
        }
        Collections.sort(ans);
        // Integer.MAX_VALUE = 2147483647  
        // Note: ans starts at least with 2 (guaranteed to have overflow if the size is great or equal 10)
        if (a > 10 || ans.size() >= 10)   return 0;
        int num = 0;
        for (int i: ans){
            num *= 10;
            num += i;
        }
        return num;
    }

  • 0
    A

    @MichaelPhelps concise and elegant solution. I like it the way it focuses the divisors between 2 and 9.


  • 0
    M
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.