解法一
暴力遍历会超时,找规律
class Solution {
public:
int countDigitOne(int n) {
int count = 0;
long i = 1;//指当前遍历的位数,1指个位,10指十位
while(n/i!=0){
long high = n/(10*i);//将当前位置的所有高位都存在high中
long cur = (n/i)%10;//将当前位存在cur中
long low = n-(n/i)*i;//将当前位置的低位存在low中
if(cur == 0) count = count + high*i;
else if(cur == 1) count = count + high*i + low +1;
else count = count + high*i + i;
i = i*10;//准备遍历下一位
}
return count;
}
};