← All solutions
September 9Medium

Count commas in range ii

  • Math

Problem

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.

Solution

class Solution:
    def countCommas(self, n: int) -> int:
        res = 0
        k = 1000
        while k <= n:
            res += n - k + 1
            k *= 1000
        return res