描述
输入一个整数 n ,求 1~n 这 n 个整数的十进制表示中 1 出现的次数
例如, 1~13 中包含 1 的数字有 1 、 10 、 11 、 12 、 13 因此共出现 6 次
注意:11 这种情况算两次
数据范围: 1≤n≤30000
进阶:空间复杂度 O(1) ,时间复杂度 O(lognn)
示例1
输入:
13
返回值:
6
示例2
输入:
0
返回值:
0
思路:
模拟,直接遍历判断个位数是否为1,然后再除10,看十位数,然后得出cnt,返回次数即可。
题解:
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
int cnt = 0;
for(int i = 1;i <= n;i++){
int n = i;
while(n){
if(n % 10 == 1)
cnt++;
n /= 10;
}
}
return cnt;
}
};
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
if (n <= 0)
return 0;
if (n < 10)
return 1;
int high = n, pow = 1;
while (high >= 10) {
high /= 10;
pow *= 10;
}
int last = n - high * pow; //除掉最高位的数字
int cnt = 0;
if (high == 1) // 如果最高位是1
cnt = last + 1;
else
cnt = pow;
return cnt + high * NumberOf1Between1AndN_Solution(pow - 1) +
NumberOf1Between1AndN_Solution(last);
}
};