Shared my C++ Solution ~


  • 0
    class Solution {
    public:
        int smallestFactorization(int a) {
            if(a < 10)
                return a;
            vector<char> candidate;
            for(int factor = 9; factor > 1 && a != 1; -- factor){
                while(a % factor == 0){
                    candidate.push_back(factor + '0');
                    a /= factor;
                }
            }
    
            if(candidate.empty() || a != 1) 
                return 0;//unable to find candidate  or  factors doesn't consist of 2~9, like 22 = 2 * 11
    
            string s;
            for_each(candidate.rbegin(), candidate.rend(), [&s](const char &c){
                s += c; 
            });
            return stoll(s) > INT_MAX ? 0 : stoi(s);
        }
    };
    

    use vector<int> candidate to recording count of factors, instead of vector<char>

    class Solution {
    public:
        int smallestFactorization(int a) {
            if(a < 10)
                return a;
            vector<int> candidate(10); //分别记录0~9数字个数
            for(int factor = 9; factor > 1 && a != 1; -- factor){
                while(a % factor == 0){
                    ++candidate[factor];
                    a /= factor;
                }
            }
            if(a != 1)
                return 0;
                
            string s;
            int idx = 0; 
            for_each(candidate.begin(), candidate.end(), [&s, &idx](const int &count){
                s += string(count, (idx++ + '0')); 
            });
            
            return stoll(s) > INT_MAX ? 0 : stoi(s);
        }
    };
    

Log in to reply
 

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