给定数字乘积的最小数字
难度:
标签:
题目描述
代码结果
运行时间: 32 ms, 内存: 16.0 MB
/*
* Leetcode Problem 2847: Smallest Number With Given Product
*
* Problem Statement:
* Given an integer n, return the smallest positive integer that has a digit product of n.
* If no such integer exists, return -1.
*
* Approach:
* 1. If n is less than 10, return n (since the smallest number with the digit product n is n itself).
* 2. Use a list to store the digits.
* 3. Iterate from 9 down to 2 and for each digit, add it to the list if it divides n.
* 4. Sort the list and convert it to a number.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SmallestNumberWithProductStream {
public static int smallestNumber(int n) {
if (n < 10) return n;
List<Integer> digits = new ArrayList<>();
for (int i = 9; i >= 2; i--) {
while (n % i == 0) {
digits.add(i);
n /= i;
}
}
if (n > 1) return -1;
Collections.sort(digits);
return digits.stream().reduce(0, (a, b) -> a * 10 + b);
}
public static void main(String[] args) {
System.out.println(smallestNumber(36)); // Output: 49
System.out.println(smallestNumber(100)); // Output: 455
System.out.println(smallestNumber(7)); // Output: 7
}
}
解释
方法:
该题解的思路是使用贪心算法的方法,寻找能够整除给定数字n的最小数字。从最大的单数位数字9开始,依次降到2,尝试用n除以这些数字,以检查能否整除。每当发现n可以被当前数字i整除时,就将i加入结果列表,并用n除以i更新n。这个过程一直持续到n不能被2到9之间的任何数字整除。最后,将结果列表逆序并连接成字符串形式,因为要返回最小的数字,较小的数字应该位于前面。如果最终n不等于1,说明n包含比9更大的质因数,这时应该返回'-1'。
时间复杂度:
O(log n)
空间复杂度:
O(log n)
代码细节讲解
🦆
为什么你选择从9开始向下至2遍历,而不是从2向上至9遍历?这种顺序对结果有什么影响?
▷🦆
当n最终不等于1,返回'-1',这是否意味着n包含大于9的质因数?能否给出一个具体的例子来说明这种情形?
▷🦆
你如何确保将因数添加到列表并最终逆序连接可以得到最小的数字?这种方法适用于所有情况吗?
▷🦆
如果n是一个质数,比如11,题解中的算法会怎么处理?
▷