您的位置:首页 > 其它

PAT (Advanced Level) Practise 1049 Counting Ones (30)

2017-07-17 13:21 555 查看

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:
12
Sample Output:
5

题意:给你一个n,问1~n中一共出现了几个1
解题思路:可以发现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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: