从下面两道题总结的规律
剑指 Offer 43. 1~n整数中1出现的次数
面试题 17.06. 2出现的次数
根据下面的题解
面试题43. 1~n 整数中 1 出现的次数(清晰图解)
进一步应用到任意数字 m 的情况
class Solution {
public int countDigit(int n, int m) {
int high = n / 10;
int low = 0;
int cur = n % 10;
int digit = 1;
int res = 0;
while(high > 0 || cur > 0){
if(cur < m){
res += high * digit;
}else if(cur == m){
res += high * digit + low + 1;
}else{
res += (high + 1) * digit;
}
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
}