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:
12Sample 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;
}
相关文章推荐
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- 【PAT】【Advanced Level】1049. Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- PAT (Advanced Level) Practise 1115 Counting Nodes in a BST (30)
- PAT (Advanced Level) Practise 1115 Counting Nodes in a BST (30)
- 【PAT甲级】1049. Counting Ones (30)
- pat甲1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1026. Table Tennis (30)
- 1022. Digital Library (30) @ PAT (Advanced Level) Practise
- PAT 解题报告 1049. Counting Ones (30)
- PAT甲级.1049. Counting Ones (30)
- PAT甲级 1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1119 Pre- and Post-order Traversals (30)
- PAT (Advanced Level) Practise 1087 All Roads Lead to Rome (30)
- PAT (Advanced Level) Practise 1131 Subway Map (30)
- 1087. All Roads Lead to Rome (30)【最短路】——PAT (Advanced Level) Practise
- PAT 1049. Counting Ones (30)