[LeetCode] Count Commas in Range II

3871. Count Commas in Range II

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

class Solution {
public:
long long countCommas(long long n) {
long long res = 0;
for(long long i = 1000, op = 1; i <= n; i = i * 1000, op++) {
long long cnt = min(i * 1000 - 1, n) - i + 1;
res += op * cnt;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-commas-in-range-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.