[Leetcode] 625. Minimum Factorization 解题报告
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode] 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:
Example 2
Input:
思路:
可以觀察到兩個事實:1)n位數一定小于n+1位的數;2)如果幾個結果都是n位數,那么將各個位上的數按照升序排列,則形成的n位數結果是最小的。所以我們的思路就是盡量讓結果的位數小,并且讓因數從大到小。所以可以讓i從9循環到2,按照順序找出a中所有9-2之間的因數(注意不是質因數),然后將它們按照升序排列,形成的結果即為題目所求。我們這里讓d < 10是為了防止int溢出。
代碼:
class Solution { public:int smallestFactorization(int a) {if (a < 2) {return a;}long l = 0;for (int i = 9, d = 0; i >= 2 && d < 10; --i) {while (a % i == 0 && d < 10) {l += i * pow(10, d++);a /= i;}}return a > 1 || l > INT_MAX ? 0 : l;} };總結
以上是生活随笔為你收集整理的[Leetcode] 625. Minimum Factorization 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: canvas学习(html5)画画
- 下一篇: 文档安全有个服务器的组,云服务器安全组是