给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。
例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。
Input
输入N(1 <= N <= 10^9)
Output
输出包含1的个数
Input示例
12
Output示例
5
打个表就能找到规律,然后一位一位递推出来即可。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=510;
ll f[11],c[11];
void init(){
ll t=1;
for(int i=1;i<=10;++i){
f[i]=i*t;
c[i]=t;
t*=10;
}
}
ll get(int x){
int q,cnt=0,s;
ll ret=0,t=1;
while(x){
cnt++;
q=x%10;
s=q;
x/=10;
ret+=s*f[cnt-1];
if(s>1) ret+=c[cnt];
else if(s==1) ret+=t;//cout<<t<<endl;
t=t+q*c[cnt];
q*=c[cnt];
}
return ret;
}
int main(){
int n;
init();
while(~scanf("%d",&n)){
printf("%lld\n",get(n));
}
return 0;
}