Smallest Divisible Digit Product I Problem
#3345
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3345.
You are given two integers n and t. Return the smallest number greater than or equal to n such that the product of its digits is divisible by t.
Example 1:
Input: n = 10, t = 2
Output: 10
Explanation:
The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.
Example 2:
Input: n = 15, t = 3
Output: 16
Explanation:
The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.
Constraints:
1 <= n <= 1001 <= t <= 10
Solution
Approach: Enumeration
Among any ten consecutive numbers one ends in 0, and its digit product is 0, which every t divides. So the search from n stops within ten steps: try n, n + 1, ..., compute each digit product, and return the first one divisible by t.
Complexity: O(log n) time and O(1) space, since at most about ten numbers are tried.
from itertools import count
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