1049. Counting Ones (30)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.
Input Specification:
Each input file contains one test case which gives the positive N (<=230).
Output Specification:
For each test case, print the number of 1's in one line.
Sample Input:12Sample Output:
5
这个题目是很有趣的,让我想了很久,在网上找了几个答案,结果没一个有像样的注释,看不懂,只能自己花了一个小时想出来了。
从0到1000输出一遍是很有必要的,有助于我们快速找到规律。我们可以很轻松的看到,100对应答案21,1000对应答案301,10000对应答案4001.....
也就是说,除了1最高位为1,每增加10^x次方答案增加的数目是恒定的xi。
递归处理第一位,比如第一位数字是a,那么我们先考虑a00000以前的所有,再递归加上a右边的位数就是答案了。
#include <iostream>
#include <vector>
using namespace std;
int w[]={0,0,1,20,300,4000,50000,600000,7000000,80000000,900000000};
//每10加1,每100加20,每1000加300.......
void init(){//这个是验算用的
int sum = 0;
for(int i = 0 ;i<2;i++)
for(int j = 0;j<10;j++)
//for(int k=0;k<10;k++)
for(int l=0;l<10;l++){
if(i==1) sum++;
if(j==1) sum++;
//if(k==1) sum++;
if(l==1) sum++;
cout<<i<<j<<l<<" "<<sum<<endl;
}
}
int pow(int t){
int l = 1;
while(t--)
l=l*10;
return l;
}
int f(int n){
if(n==0)
return 0;
if(n<10)
return 1;
int wei=0; //有多少位
int m = n;
while(m)
{
wei++;
m/=10;
}
int no = pow(wei-1); //当前位的最小值
int asdasd=n/no; //n是不是1开头的啊
if(asdasd==1){
int t = n%no;
return w[wei]+t+1+f(t);
//比如 1234就要300 + 234 + 1,这个234+1表示从1000到1234一共有235个千位1,f(t)求百位以后的数
}
else
{ //若是asdasd第一位比1大
int t = n%no;
return w[wei]*(asdasd)+no+f(t);
}
}
int main()
{
//init();
int n;
cin>>n;
cout<<f(n)<<endl;
return 0;
}