日期:2026年8月6日
LeetCode 題目連結:3345. Smallest Divisible Digit Product I
解題想法
簡單題。題目給兩個整數 $n$、$t$,要找出大於、等於 $n$ 且數字乘積可以被 $t$ 整除的最小整數。基本上答案不會太大,只要用一個 while 迴圈,從 $n$ 開始往上檢查數字乘積是否可以被 $t$ 整除,如果可以整除就回傳目前 $n$ 的值,反之則將 $n$ 加 $1$。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.36 MB, beats 32.93%.
class Solution:
def smallestNumber(self, n: int, t: int) -> int:
while True:
x = n
d = 1
while x:
d *= x % 10
x //= 10
if d % t == 0:
return n
n += 1
return -1
C++ 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.52 MB, beats 73.40%.
class Solution {
public:
int smallestNumber(int n, int t) {
while(true) {
int x = n, d = 1;
while(x) {
d *= x % 10;
x /= 10;
}
if (d%t == 0) return n;
n++;
}
return -1;
}
};
C 語言程式碼
Runtime: 0 ms, beats 100.00%. Memory: 9.14 MB, beats 16.00%.
int smallestNumber(int n, int t) {
while(true) {
int x = n, d = 1;
while(x) {
d *= x % 10;
x /= 10;
}
if (d%t == 0) return n;
n++;
}
return -1;
}
沒有留言:
張貼留言