← All problems

3871. Count Commas in Range II

MediumOpen on LeetCodeProblem statement

Problem Statement

3871. Count Commas in Range II

Medium


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:

Java — direct

Source file
class 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);
    }
}