[LeetCode] Smallest Number With Given Digit Product

2847. Smallest Number With Given Digit Product

Given a positive integer n, return a string representing the smallest positive integer such that the product of its digits is equal to n, or "-1" if no such number exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string smallestNumber(long long n) {
if(n == 1) return "1";
vector<int> cnt(10);
auto work = [&](int x) {
while(n % x == 0) {
n /= x;
cnt[x] += 1;
}
};
for(auto x : {8,9,6,4,2,3,5,7}) work(x);
if(n != 1) return "-1";
string res = "";
for(int i = 2; i <= 9; i++) res += string(cnt[i],'0' + i);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/09/PS/LeetCode/smallest-number-with-given-digit-product/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.