3870. Count Commas in Range
EasyView on LeetCode
Problem Overview
Commas appear every three digits from the right.
Intuition
Commas appear every three digits from the right. Here n is at most 10^5, so numbers never reach a second comma layer. Every integer from 1000 through n contributes exactly one comma.
Algorithm
- 1If n is below 1000, return 0.
- 2Otherwise return n minus 999.
- 3That counts integers 1000, 1001, ..., n.
Example Walkthrough
Input: n = 1002
- 1.1000, 1001, and 1002 each use one comma.
- 2.Count is 1002 - 999 = 3.
Output: 3
Common Pitfalls
- •Do not loop thresholds unless n can exceed 999999.
- •Use n - 999, not n - 1000, to include 1000 itself.
- •Return 0 for n <= 999 instead of a negative value.
- •Part II allows huge n and needs the 1000^k threshold sum.
3870.cs
C#
// Approach: n <= 10^5, so only numbers >= 1000 get a comma and each gets
// exactly one. Count is max(0, n - 999).
// Complexity: O(1) time and O(1) extra space.
public class Solution
{
public int CountCommas(int n)
{
return Math.Max(0, n - 999);
}
}
Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)
- 70. Climbing Stairs(Easy)