日期: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$,因此答案只有兩種:
- $n < 1000$,答案 $0$。
- $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;
}
沒有留言:
張貼留言