1049 Counting Ones
思路:
通过找规律求解,
分为三种情况,
eg:121000,
(1)从后向前数,第三位是0,就有121*100个1可以表示
(2)第4位是1,就有12*1000+1000+1个1
(3)第5为是2,就有(1+1)*10000个1.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main(void)
{
int n,i,sum=0,x,tp=1;//tp记录当前位的大小
scanf("%d",&n);
while(n/tp){
int le=n/(tp*10); //左边数
int ri=n%tp; //右边数
x=n/tp%10; //当前这一位的数字
if(x==0) sum+=le*tp; //如果是0,就是当左边数*当前位
else if(x==1) sum+=le*tp+ri+1; //如果是1,就是左边数*当前位+右边数+1
else sum+=(le+1)*tp; //如果大于1,就是(左边数+1)*当前位
tp*=10; //更新当前位
}
printf("%d\n",sum);
return 0;
}