3870. Count Commas in Range
SourceWeekly Contest 493 Q1DifficultyEasyRating1149
Description
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.
Example 1:
Input: n = 1002
Output: 3
Explanation:
The numbers "1,000", "1,001", and "1,002" each contain one comma, giving a total of 3.
Example 2:
Input: n = 998
Output: 0
Explanation:
All numbers from 1 to 998 have fewer than four digits. Therefore, no commas are used.
Constraints:
1 <= n <= 105
Solutions
Solution 1: Brain Teaser
Thinking
Count thousands-separator commas used when writing \([1,n]\). \(n \le 10^5\), so numbers have at most six digits and at most one comma each.
\(1\) through \(999\) have none; each integer from \(1000\) to \(n\) has exactly one.
The answer is \(\max(0,n-999)\).
Constant time, no enumeration.
Numbers from 1 to 999 contain no commas, so when \(n\) is less than or equal to 999, the answer is 0.
Since the range of \(n\) is \([1, 10^5]\), when \(n\) is greater than or equal to 1000, each number contains exactly one comma, so the answer is \(n - 999\).
Therefore, the answer is \(\max(0, n - 999)\).
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 | |
1 2 3 4 5 | |
1 2 3 4 5 6 | |
1 2 3 | |
1 2 3 | |