Count Commas in Range II Problem
#3871
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3871.
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 <= 10^15
Solution
Approach: Counting by Magnitude
A number gets one comma for each power 1000, 10^6, 10^9, ... it reaches. So start at x = 1000 and, while x <= n, add n - x + 1 (the numbers from x to n, each of which has at least this many commas), then multiply x by 1000.
Complexity: O(log n) time and O(1) space.
class Solution:
def countCommas(self, n: int) -> int:
ans = 0
x = 1000
while x <= n:
ans += n - x + 1
x *= 1000
return ans