算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 最小因式分解,我们先来看题面:
https://leetcode.cn/problems/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.
给定一个正整数 a,找出最小的正整数 b 使得 b 的所有数位相乘恰好等于 a。
如果不存在这样的结果或者结果不是 32 位有符号整数,返回 0。
示例
样例 1
输入:
48
输出:
68
样例 2
输入:
15
输出:
35
解题
https://blog.youkuaiyun.com/weixin_44171872/article/details/108987095
主要思路:
(1)先处理特殊情形,既为个位数的数时,直接返回原始值即可;
(2)将数字使用个位数的数字进行循环整除,为了保证获得的数字尽可能的小,个位数字从大到小,将获得各个位组成数字;
(3)判断最终的a的值是否依旧大于9,若是,则说明不能分解为个位数的成绩,然后判断获得值是否大于INT_MAX,若是,说明不符合要求,都返回0,否则返回获得的值;
class Solution {
public:
int smallestFactorization(int a) {
if(a<10){//个位数的特殊情形直接返回结果
return a;
}
long res=0;
long step=1;
//分解各个数字
for(int i=9;i>=2;--i){
while(a%i==0){
res=step*i+res;
step*=10;
a/=i;
}
}
//判断是否不满足要求
if(a>9||res>INT_MAX){
return 0;
}
return res;
}
};
上期推文: