输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
class Solution {
public int countDigitOne(int n) {
int digit = 1;
int low = 0;
int high = n / 10;
int curr = n % 10;
int res = 0;
while (curr != 0 || high != 0) {
if (curr == 0) {
res = res + high * digit;
} else if (curr == 1) {
res = res + high * digit + low + 1;
} else {
res = res + (high + 1) * digit;
}
low = low + curr * digit;
digit *= 10;
n = n / 10;
high = n / 10;
curr = n % 10;
}
return res;
}
}