置頂

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

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

熱門文章

2026年8月22日 星期六

LeetCode 解題筆記:3622. Check Divisibility by Digit Sum and Product

作者:王一哲
日期:2026年8月22日


LeetCode 題目連結:3622. Check Divisibility by Digit Sum and Product

解題想法


簡單題。題目給一個整數 $n$,假設 $n$ 的每個數字相加為 $dsum$,每個數字相乘為 $prod$,回傳 $n$ 是否可以被 $dsum + prod$ 整除。建立變數 $x = n$、$dsum = 0$、$prod = 1$,用一個 while 迴圈取出 $x$ 的每個數字,計算 $dsum$ 及 $prod$,最後回傳 $n % (dsum + prod) == 0$。也可以將 $n$ 轉成字串 $s$,再依序由 $s$ 讀取每個位數的字元,計算 $prod$ 及 $dsum$,速度也很快。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.34 MB, beats 24.05%.
class Solution:
    def checkDivisibility(self, n: int) -> bool:
        x, prod, dsum = n, 1, 0
        while x:
            d = x % 10
            x //= 10
            prod *= d
            dsum += d
        return n % (prod + dsum) == 0


Runtime: 0 ms, beats 100.00%. Memory: 19.32 MB, beats 24.05%.
class Solution:
    def checkDivisibility(self, n: int) -> bool:
        s = str(n)
        prod, dsum = 1, 0
        for c in s:
            d = int(c)
            prod *= d
            dsum += d
        return n % (prod + dsum) == 0


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 7.82 MB, beats 37.42%.
class Solution {
public:
    bool checkDivisibility(int n) {
        int x = n, prod = 1, dsum = 0;
        while(x) {
            int d = x % 10;
            x /= 10;
            prod *= d;
            dsum += d;
        }
        return n % (prod + dsum) == 0;
    }
};


Runtime: 0 ms, beats 100.00%. Memory: 8.15 MB, beats 5.82%.
class Solution {
public:
    bool checkDivisibility(int n) {
        string s = to_string(n);
        int prod = 1, dsum = 0;
        for(char c : s) {
            int d = c - '0';
            prod *= d;
            dsum += d;
        }
        return n % (prod + dsum) == 0;
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 8.47 MB, beats 71.96%.
bool checkDivisibility(int n) {
    int x = n, dsum = 0, prod = 1;
    while(x) {
        int d = x % 10;
        dsum += d;
        prod *= d;
        x /= 10;
    }
    return n % (dsum + prod) == 0;
}


沒有留言:

張貼留言