题目来源: 整数中1出现的次数(从1到n整数中1出现的次数)_牛客题霸_牛客网
描述
输入一个整数 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
我的代码:
找到了一个很清晰的解析,答案解析:力扣
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
int digit=1,re=0;
int x=n;
int low=0,high=0;
int cur=x%10;
while(x/10>0 || cur>0){
cout<<x/10<<" "<<cur<<endl;
high = n/(digit*10);
low = n%digit;
cout<<high<<" "<<low<<" "<<cur<<endl;
if(cur==0){ //如果当前为为0
re+=high*digit;
cout<<"re0:"<<re<<endl;
}else if(cur==1){//如果当前为为1
re+=high*digit+low+1;
cout<<"re1:"<<re<<endl;
}else if(cur>=2){//如果当前为为2
re+=(high+1)*digit;
cout<<"re2:"<<re<<endl;
}
x=x/10;
cur = x%10;
digit*=10;
}
return re;
}
};