[LeetCode] Count Commas in Range

3870. Count Commas in Range

You are given an integer n.

Return the total number of commas used when writing all integers from [1, n] (inclusive) in standard number formatting.

In standard formatting:

  • A comma is inserted after every three digits from the right.
  • Numbers with fewer than 4 digits contain no commas.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int countCommas(int n) {
int res = 0;
for(int i = 1000, op = 0, nxt = 1000; i <= n; i++) {
if(i == nxt) {
nxt = nxt * 1000;
op++;
}
res += op;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-commas-in-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.