LeetCode刷题实战233:数字 1 的个数
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
示例
示例 1:
输入:n = 13
输出:6
示例 2:
输入:n = 0
输出:0
解题
class Solution {
public:
int countDigitOne(int n) {
int res = 0, a = 1, b = 1;
while (n > 0) {
res += (n + 8) / 10 * a + (n % 10 == 1) * b;
b += n % 10 * a;
a *= 10;
n /= 10;
}
return res;
}
};
评论
