Back to Month
MEDIUM 09 Sep 2026 View on LeetCode

3871. Count Commas in Range II

</> Solution

class Solution {
    public long countCommas(long n) {
        long result = 0;
        
        long threshold = 1000L; // 4-digit numbers → 1 comma
        
        while (threshold <= n) {
            result += (n - threshold + 1);
            threshold *= 1000L; // next comma level
        }
        
        return result;
    }
}

TIME COMPLEXITY

O(log₁₀₀₀(n))

SPACE COMPLEXITY

O(1)

TOPICS

Counting Math Simulation