题目:https://leetcode-cn.com/problems/number-of-digit-one/
代码:https://leetcode-cn.com/problems/number-of-digit-one/solution/shu-zi-1-de-ge-shu-by-leetcode/
给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
思路:计算10进制数每个位上1的贡献个数,代码实现上卡了
class Solution {
public:
int countDigitOne(int n) {
int countr = 0;
for (long long i = 1; i <= n; i *= 10) {
long long divider = i * 10;
countr += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i);
}
return countr;
}
};