置頂

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

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

熱門文章

2026年9月8日 星期二

LeetCode 解題筆記:3870. Count Commas in Range

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


LeetCode 題目連結:3870. Count Commas in Range

解題想法


困難題。題目給一個正整數 $n$ $(1 \leq n \leq 10^5)$,計算 $1$ 到 $n$ 共有幾個分隔數字的逗號,小於 $1000$ 的數字不需要加逗號,大於等於 $1000$ 的數字,每隔 $3$ 位數加 $1$ 個逗號。由於 $n$ 最大只到 $10^5$,因此答案只有兩種:
  1. $n < 1000$,答案 $0$。
  2. $n \geq 1000$,答案 $n - 999$,因為 $1000$ 也要加逗號。


Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.22 MB, beats 46.53%.
class Solution:
    def countCommas(self, n: int) -> int:
        if n < 1000: return 0
        return n - 999


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 8.57 MB, beats 51.38%.
class Solution {
public:
    int countCommas(int n) {
        if (n < 1000) return 0;
        return n - 999;
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.14 MB, beats 64.94%.
int countCommas(int n) {
    if (n < 1000) return 0;
    return n - 999;
}


沒有留言:

張貼留言