[LeetCode] 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

 

這道題給了我們一個數字,讓我們進行因數分解,讓我們找出因數組成的最小的數字。從題目中的例子可以看出,分解出的因數一定是個位數字,即范圍是[2, 9]。那我們就可以從大到小開始找因數,首先查找9是否是因數,是要能整除a,就是其因數,如果是的話,就加入到結果res的開頭,a自除以9,我們用while循環查找9,直到取出所有的9,然后取8,7,6...以此類推,如果a能成功的被分解的話,最后a的值應該為1,如果a值大於1,說明無法被分解,返回true。最后還要看我們結果res字符轉為整型是否越界,越界的話還是返回0,參見代碼如下:

 

解法一:

class Solution {
public:
    int smallestFactorization(int a) {
        if (a == 1) return 1;
        string res = "";
        for (int k = 9; k >= 2; --k) {
            while (a % k == 0) {
                res = to_string(k) + res;
                a /= k;
            }
        }
        if (a > 1) return 0;
        long long num = stoll(res);
        return num > INT_MAX ? 0 : num;
    }
};

 

下面這種方法跟上面解法思路很像,只是結果res沒有用字符串,而是直接用的長整型,我們每次在更新完res的結果后,判斷一次是否越整型的界,越了就直接返回0,其他部分和上面沒有什么區別,參見代碼如下:

 

解法二:

class Solution {
public:
    int smallestFactorization(int a) {
        if (a < 10) return a;
        long long res = 0, cnt = 1;
        for (int i = 9; i >= 2; --i) {
            while (a % i == 0) {
                res += cnt * i;
                if (res > INT_MAX) return 0;
                a /= i;
                cnt *= 10;
            }
        }
        return (a == 1) ? res : 0;
    }
};

 

參考資料: 

https://discuss.leetcode.com/topic/92920/concise-c-solution-10-lines-3ms

https://discuss.leetcode.com/topic/92998/c-clean-code-7-line-3-solutions/2

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM