置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年8月6日 星期四

LeetCode 解題筆記:3345. Smallest Divisible Digit Product I

作者:王一哲
日期: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;
}


沒有留言:

張貼留言