Skip to main content

3870. Count Commas in Range

Easy
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 <= 10^5

解題思路​

要算出總共有幾個逗號。
然後測資很少,只有 1 <= n <= 10510^5,所以要考慮的只有三種狀況。

var countCommas = function (n) {
if (n === 1000000) return 999002; // 最大值 1000000 的狀況,會變成 1,000,000,有兩個逗號,可以先用 n - 1000 + 1 算出除他之外其他值總和,最後再加二,會變成 999002。
if (n < 1000) return 0; // 小於 1000 的狀況,沒有逗號
return n - 1000 + 1; // 介於 1000 到最大值的狀況,可以用 n - 1000 + 1 這個公式算出。
};

心得​

甘單,不到五分鐘搞定😎