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~9出现了1个1,0~99出现了10+1*10个1,0~999出现了100+20*10个1......然后可以根据这个规律去打表,之后就可以根据这个表去进行模拟
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
LL a[16],n,x[16];
void init()
{
a[0]=0,a[1]=1;
LL x=10;
for(int i=2;i<16;i++) a[i]=x+a[i-1]*10,x*=10;
}
int main()
{
init();
while(~scanf("%lld",&n))
{
int cnt=0;
LL ans=0,m=n,k=1;
while(n) {x[cnt++]=n%10,n/=10,k*=10;}
k/=10;
for(int i=cnt-1;i>=0;i--)
{
ans+=a[i]*x[i];
if(x[i]==1) ans+=(m-k*x[i]+1);
if(x[i]>1) ans+=k;
m-=(k*x[i]);
k/=10;
}
printf("%lld\n",ans);
}
return 0;
}