Skip to main content

3871. Count Commas in Range II

Medium
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^15

解題思路​

要算出總共有幾個逗號。
但測資比較大,所以不能和上一題目一樣暴力解。
這次改用計算ㄉ。

var countCommas = function (n) {
let base = 1000; // 因為每多三個 0 才會多一個逗號,故 base 設定為 1000
let result = 0; // 總共有幾個逗號,最少是 0 個

while (n >= base) {
result += n - base + 1; // 算出這輪共有幾個逗號
base *= 1000; // 進到下一輪,base 需要乘上 1000
}

return result;
};

心得​

比想像中還容易理解一點。