剑指 offer 43 1~n 整数中1出现的次数
class Solution {
public int countDigitOne(int n) {
int res = 0;
// int tmp = n;
int high = n/10;
int digit = 1;
int cur = n%10;
int low = 0;
while(high !=0 || cur !=0){
if(cur == 0){
res += high * digit;
}else if(cur == 1){
res += high * digit + low+1;
}else{
res += high * digit +digit;
}
low = low + cur*digit;
digit *= 10;
cur = high%10;
high = high/10;
}
return res;
}
}
时间复杂度
O
(
l
o
g
n
)
O(logn)
O(logn),循环次数是数字
n
n
n的位数。
空间复杂度
O
(
1
)
O(1)
O(1)。