给出一个数字n,求1~n的所有数字里面出现1的个数
找数学规律,一开始我也想不出来,看了别人解释还是没看懂,直到看到这位老哥的博客才懂了:https://www.cnblogs.com/caiyishuai/p/11483265.html
AC代码:
#include<bits/stdc++.h>
using namespace std;
int n;
int num=0;
int main(){
cin>>n;
int factor = 1;
int higher,lower,cur;//高位,低位,当前位
while(n/factor!=0){//依次取个、十、百、千……
higher = n/(factor*10);
cur=(n/factor)%10;
lower=n%factor;
if(cur==0){
num+=higher*factor;
}else if(cur==1){
num+=higher*factor+lower+1;
}else{
num+=higher*factor+factor;
}
factor = factor * 10;
}
cout<<num;
return 0;
}