Smallest Divisible Digit Product I (LeetCode 3345): Solution and Explanation
Given n and t, return the smallest number at least n whose digit product is a multiple of t.
Intuition
The answer is the first number from n upward that passes a simple test, so the natural plan is to try n, n + 1, n + 2 and so on.
The test itself is cheap: multiply the digits using x % 10 and x // 10, then check product % t == 0.
The search is guaranteed to be short. Any number ending in 0 has a digit product of 0, and 0 is divisible by every t. One of any ten consecutive numbers ends in 0, so at most ten candidates are checked.
Approach: Count upward from n
- Set
x = n. - Compute
p, the product of the digits ofx. - If
p % t == 0, returnx. - Otherwise increase
xby one and repeat.
Step-by-step example
n = 10, t = 2
- x = 10. Its digits are 1 and 0, so p = 1 x 0 = 0.
- 0 % 2 = 0, so 10 already works.
- Return 10.
Code: Python, Java, C++
1class Solution:
2 def smallestNumber(self, n: int, t: int) -> int:
3 x = n
4 while True:
5 p = 1
6 y = x
7 while y > 0:
8 p *= y % 10
9 y //= 10
10 if p % t == 0:
11 return x
12 x += 11class Solution {
2 public int smallestNumber(int n, int t) {
3 int x = n;
4 while (true) {
5 int p = 1;
6 for (int y = x; y > 0; y /= 10) {
7 p *= y % 10;
8 }
9 if (p % t == 0) {
10 return x;
11 }
12 x++;
13 }
14 }
15}1class Solution {
2public:
3 int smallestNumber(int n, int t) {
4 int x = n;
5 while (true) {
6 int p = 1;
7 for (int y = x; y > 0; y /= 10) {
8 p *= y % 10;
9 }
10 if (p % t == 0) {
11 return x;
12 }
13 x++;
14 }
15 }
16};Time and space complexity
O(log n)
At most 10 candidates are tried and each digit product takes one step per digit.
O(1)
Only x, the product and a working copy are stored.
Other approaches
Jump straight to the next multiple of 10 (time O(log n), space O(1))
Check the numbers from n up to the next number ending in 0, since that one always works. It is the same search with an explicit upper bound.
String digits (time O(log n), space O(log n))
Multiply int(c) over str(x) instead of using % 10. Easy to read, with a small string allocation per candidate.
Common mistakes
- Starting the product at 0 instead of 1, which makes every product 0 and returns n every time.
- Searching for numbers strictly greater than n. The answer can be n itself.
- Forgetting that a 0 digit makes the product 0, which counts as divisible.
Frequently asked questions
Why does the loop always stop?
Within any ten consecutive numbers one ends in the digit 0. Its product is 0, and 0 is divisible by every t from 1 to 10.
Is 0 really divisible by t?
Yes. 0 = 0 x t with no remainder, so 0 % t is 0 for any positive t.
What changes in the harder version of this problem?
Version II gives n as a huge string and forbids zero digits, so counting upward no longer works and a greedy construction over prime factors is needed.