Skip to main content
Back to problems
#3870
Easy Algorithms

Count commas in range

Math
68.6% acceptance
Mar 31, 2026
37
3
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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_commas(n: i32) -> i32 {
    // Numbers with 4+ digits (1000-99999 within constraint n<=10^5) have 1 comma each.
    // Numbers with 7+ digits would have 2 commas, but n<=10^5 so max 6 digits = 1 comma.
    if n < 1000 {
      0
    } else {
      n - 999
    }
  }
}