置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年7月7日 星期二

LeetCode 解題筆記:3754. Concatenate Non-Zero Digits and Multiply by Sum I

作者:王一哲
日期:2026年7月7日


LeetCode 題目連結:3754. Concatenate Non-Zero Digits and Multiply by Sum I

解題想法


簡單題。題目給一個整數 $n$,範圍為 $0 \leq n \leq 10^9$,要找出 $n$ 之中所有的非零數字並依照順序組成另一個整數 $x$,將這些非零整數相加為 $sum$,回傳 $x \times sum$。為了檢查 $n$ 的每個位數,可以使用 while 迴圈,迴圈每次運作時計算 $n % 10$ 取出個位數,再計算 $n //= 10$ 將 $n$ 變為 1/10 倍;另一個想法是直接將 $n$ 轉成字串,從字串開頭依序讀取字元。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.42 MB, beats 14.68%.
class Solution:
    def sumAndMultiply(self, n: int) -> int:
        x, isum, base = 0, 0, 1
        while n:
            last = n % 10
            n //= 10
            if last != 0:
                x += last * base
                isum += last
                base *= 10
        return x * isum

Runtime: 3 ms, beats 22.16%. Memory: 19.10 MB, beats 96.95%.
class Solution:
    def sumAndMultiply(self, n: int) -> int:
        if n == 0: return 0
        
        isum = 0
        s, x = str(n), ""
        for c in s:
            if c != '0':
                x += c
                isum += int(c)
        return int(x) * isum


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.01 MB, beats 51.79%.
class Solution {
public:
    long long sumAndMultiply(int n) {
        long long x = 0, isum = 0, base = 1;
        while(n > 0) {
            int last = n % 10;
            n /= 10;
            if (last != 0) {
                x += last * base;
                isum += last;
                base *= 10;
            }
        }
        return x * isum;
    }
};

Runtime: 0 ms, beats 100.00%. Memory: 9.22 MB, beats 27.38%.
class Solution {
public:
    long long sumAndMultiply(int n) {
        if (n == 0) return 0;

        string s = to_string(n), x;
        long long isum = 0;
        for(char c : s) {
            if (c != '0') {
                x += c;
                isum += c - '0';
            }
        }
        return stoll(x) * isum;
    }
};


沒有留言:

張貼留言