数字 1 的个数
给定一个整数 n
,计算所有小于等于 n
的非负整数中数字 1
出现的个数。
示例 1:
输入:n = 13 输出:6
示例 2:
输入:n = 0 输出:0
提示:
0 <= n <= 10^9
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countDigitOne(int n)
{
int cnt = 0;
for (long int i = 1; i <= n; i *= 10)
{
int a = n / i, b = n % i;
cnt += (a + 8) / 10 * i + (a % 10 == 1) * (b + 1);
if (i == 1000000000)
break;
}
return cnt;
}
};