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 <= 1015
Solutions
I knew there was some math wizardry present, didn't bother attempting to solve.
Language: javascript(2026-09-09 08:55)DONE
CPU Performance100.00%
Memory Performance10.19%
/**
* @param {number} n
* @return {number}
*/
var countCommas = function(n) {
let temp = 1_000;
let res = 0;
while (temp <= n) {
res += n - temp + 1;
temp *= 1_000;
}
return res;
};