1. 程式人生 > >leetcode -625-Minimum Factorization

leetcode -625-Minimum Factorization

-- ott clear col ati amp tco -1 tput

leetcode -625-Minimum Factorization

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

題解:

    題目的關鍵在於a的range, 註意當 a < 10 的情況。   

    同時,需要 vt 的size小於10,32-bit的integer的最高位數是10位,但是最高位的範圍是 2,1......, 一定不存在1且最小只能是2,所以只能保留9位。

class Solution {
public:
    int smallestFactorization(int a) {
        if(a < 10){
            return a; 
        }
        vector<int> vt; 
        for(int i=9; i>=2; --i){
            if(a == 1){
                break; 
            }
            while(a%i == 0){
                vt.push_back(i); 
                a = a/i; 
            }
        }
        if(a == 1 && vt.size() <= 9){
            int ans = 0; 
            for(int i=vt.size()-1; i>=0; --i){
                ans = 10*ans + vt[i]; 
            }
            return ans; 
        }else{
            return 0; 
        }
    }
};

  

leetcode -625-Minimum Factorization