跳转至

3870. 统计范围内的逗号

题目描述

给你一个整数 n

返回将所有从 [1, n](包含两端)范围内的整数以 标准 数字格式书写时所用到的 逗号总数

 标准 格式中:

  • 从右边开始,每 三位 数字后插入一个逗号。
  • 位数 少于四位 的数字不包含逗号。

 

示例 1:

输入: n = 1002

输出: 3

解释:

数字 "1,000""1,001""1,002" 每个都包含一个逗号,总计 3 个逗号。

示例 2:

输入: n = 998

输出: 0

解释:

从 1 到 998 的所有数字位数都少于四位,因此没有使用逗号。

 

提示:

  • 1 <= n <= 105

解法

方法一:脑筋急转弯

从 1 到 999 的数字都不包含逗号,因此当 \(n\) 小于等于 999 时,答案为 0。

由于 \(n\) 的范围是 \([1, 10^5]\),当 \(n\) 大于等于 1000 时,每个数字都包含一个逗号,此时答案为 \(n - 999\)

因此,答案为 \(\max(0, n - 999)\)

时间复杂度 \(O(1)\),空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def countCommas(self, n: int) -> int:
        return max(0, n - 999)
1
2
3
4
5
class Solution {
    public int countCommas(int n) {
        return Math.max(0, n - 999);
    }
}
1
2
3
4
5
6
class Solution {
public:
    int countCommas(int n) {
        return max(0, n - 999);
    }
};
1
2
3
func countCommas(n int) int {
    return max(0, n-999)
}
1
2
3
function countCommas(n: number): number {
    return Math.max(0, n - 999);
}

评论