[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:

48 
Output:
68

Example 2
Input:

15
Output:
35

思路

可以观察到两个事实: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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值