LeetCode 题解工作台
最小可整除数位乘积 I
给你两个整数 n 和 t 。请你返回大于等于 n 的 最小 整数,且该整数的 各数位之积 能被 t 整除。 示例 1: 输入: n = 10, t = 2 输出: 10 解释: 10 的数位乘积为 0 ,可以被 2 整除,所以它是大于等于 10 且满足题目要求的最小整数。 示例 2: 输入: n =…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·enumeration
答案摘要
我们注意到,每 个数里一定会出现数位乘积为 的整数,因此我们可以直接枚举大于等于 的整数,直到找到一个数位乘积能被 整除的整数。 时间复杂度 $O(\log n)$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
给你两个整数 n 和 t 。请你返回大于等于 n 的 最小 整数,且该整数的 各数位之积 能被 t 整除。
示例 1:
输入:n = 10, t = 2
输出:10
解释:
10 的数位乘积为 0 ,可以被 2 整除,所以它是大于等于 10 且满足题目要求的最小整数。
示例 2:
输入:n = 15, t = 3
输出:16
解释:
16 的数位乘积为 6 ,可以被 3 整除,所以它是大于等于 15 且满足题目要求的最小整数。
提示:
1 <= n <= 1001 <= t <= 10
解题思路
方法一:枚举
我们注意到,每 个数里一定会出现数位乘积为 的整数,因此我们可以直接枚举大于等于 的整数,直到找到一个数位乘积能被 整除的整数。
时间复杂度 ,空间复杂度 。
class Solution:
def smallestNumber(self, n: int, t: int) -> int:
for i in count(n):
p = 1
x = i
while x:
p *= x % 10
x //= 10
if p % t == 0:
return i
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate explain their reasoning behind choosing a brute force solution?
- question_mark
Does the candidate optimize the search process when possible?
- question_mark
Is the candidate able to identify edge cases like numbers with zero as a digit?
常见陷阱
外企场景- error
Failing to correctly compute the product of the digits, especially when digits contain zero.
- error
Overcomplicating the solution instead of using a straightforward brute force approach.
- error
Not checking enough numbers or missing edge cases where digit products are automatically divisible (e.g., numbers containing zero).
进阶变体
外企场景- arrow_right_alt
What if t is larger than any possible digit product?
- arrow_right_alt
How would the solution change if the range of n was significantly larger?
- arrow_right_alt
Can you optimize the digit product calculation to avoid redundant work?