Input: k =2, digit1 =0, digit2 =2Output: 20Explanation:
20is the first integer larger than 2, a multiple of 2, and comprised of only the digits 0 and/or 2.
Example 2:
1
2
3
4
Input: k =3, digit1 =4, digit2 =2Output: 24Explanation:
24is the first integer larger than 3, a multiple of 3, and comprised of only the digits 4 and/or 2.
Example 3:
1
2
3
Input: k =2, digit1 =0, digit2 =0Output: -1Explanation: No integer meets the requirements so return-1.
We want the smallest number > k, a multiple of k, and made only of two digits. This is a classic shortest-path-in-string-space problem, solved by BFS: generate numbers by appending allowed digits, and check divisibility and size.
#include<queue>#include<string>usingnamespace std;
classSolution {
public:int findInteger(int k, int d1, int d2) {
if (d1 ==0&& d2 ==0) return-1;
queue<longlong> q;
for (int d : {d1, d2}) {
if (d !=0) q.push(d);
}
while (!q.empty()) {
longlong x = q.front(); q.pop();
if (x > k && x % k ==0) return x <= INT32_MAX ? (int)x : -1;
if (x > INT32_MAX /10) continue;
for (int d : {d1, d2}) {
longlong nx = x *10+ d;
if (nx > INT32_MAX) continue;
q.push(nx);
}
}
return-1;
}
};
import java.util.*;
classSolution {
publicintfindInteger(int k, int d1, int d2) {
if (d1 == 0 && d2 == 0) return-1;
Queue<Long> q =new LinkedList<>();
for (int d : newint[]{d1, d2}) {
if (d != 0) q.offer((long)d);
}
while (!q.isEmpty()) {
long x = q.poll();
if (x > k && x % k == 0) return x <= Integer.MAX_VALUE? (int)x : -1;
if (x > Integer.MAX_VALUE/ 10) continue;
for (int d : newint[]{d1, d2}) {
long nx = x * 10 + d;
if (nx > Integer.MAX_VALUE) continue;
q.offer(nx);
}
}
return-1;
}
}
from collections import deque
classSolution:
deffindInteger(self, k, d1, d2):
if d1 ==0and d2 ==0:
return-1 q = deque()
for d in {d1, d2}:
if d !=0:
q.append(d)
while q:
x = q.popleft()
if x > k and x % k ==0:
return x if x <=2**31-1else-1if x > (2**31-1) //10:
continuefor d in {d1, d2}:
nx = x *10+ d
if nx >2**31-1:
continue q.append(nx)
return-1