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:
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 <= 1015class Solution {
public long countCommas(long n) {
int digits = (int) Math.log10(n) + 1;
// Correct floating-point rounding near powers of 10
if (digits > 1 && Math.pow(10, digits - 1) > n) {
digits--;
}
if (digits < 4)
return 0L;
if (digits < 7)
return n - 999L;
if (digits < 10)
return 2L * (n - 999_999L)
+ (999_999L - 999L);
if (digits < 13)
return 3L * (n - 999_999_999L)
+ 2L * (999_999_999L - 999_999L)
+ (999_999L - 999L);
if (digits < 16)
return 4L * (n - 999_999_999_999L)
+ 3L * (999_999_999_999L - 999_999_999L)
+ 2L * (999_999_999L - 999_999L)
+ (999_999L - 999L);
return 5L * (n - 999_999_999_999_999L)
+ 4L * (999_999_999_999_999L - 999_999_999_999L)
+ 3L * (999_999_999_999L - 999_999_999L)
+ 2L * (999_999_999L - 999_999L)
+ (999_999L - 999L);
}
}class Solution {
public long countCommas(long n) {
long lt = 1000, rt, commaCt = 1, ans = 0;
while (lt <= n) {
rt = Math.min(n, lt * 1000 - 1);
ans += commaCt * (rt - lt + 1);
lt *= 1000;
commaCt++;
}
return ans;
}
}