一样的题:剑指 Offer 43. 1~n整数中1出现的次数 - 力扣(LeetCode)
一个一个得取模取余算应该是不行的
大佬题解:详细通俗的思路分析,多解法 - 数字 1 的个数 - 力扣(LeetCode)
class Solution {
public:
int countDigitOne(int n) {
int res = 0;
long digit = 1;
int high = n / 10, cur = n%10, low = 0;//高位,当前位,低位
while(high != 0 || cur != 0){
cout << high << " " << low << endl;
if(cur == 0) res += high * digit;
else if(cur == 1) res += high * digit + low + 1;
else res += (high+1)*digit;
low += cur*digit;//左移,更新低位
cur = high % 10;//更新当前位
high /= 10;//更新高位
digit *= 10;
}
return res;
}
};