题目
代码(首刷看解析)
🔗:面试题43. 1~n 整数中 1 出现的次数(清晰图解)
class Solution {
public:
unordered_map<int, int> map;
int countDigitOne(int n) {
long digit = 1, res = 0;
int high = n / 10, cur = n % 10, low = 0;
while(high || cur) {
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;
}
};