PAT 1049. Counting Ones (30)
2017-08-30 17:31
387 查看
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
先放我的代码。思路是逐位的数1
#include<string> #include<stdio.h> #include<iostream> #include<string.h> #include<queue> #include<algorithm> #include<map> #include<vector> using namespace std; char a[100]; int n; int tmp=n; int p=0; long long sum=0; int num(int y) { int ssmm=0; int p=0; int k=1; if(y<0) return 1; while(p<=y) { ssmm+=k*(a[p]-'0'); k*=10; p++; } return ssmm+1; } void compute(int x) { int now=n; int k=1; for(int i=0;i<x;i++) k*=10; for(int i=0;i<x+1;i++) now/=10; sum+=now*k; if(a[x]>'1') sum+=k; else if(a[x]=='1') sum+=num(x-1); } int main() { cin>>n; tmp=n; while(tmp>0) { int zz=tmp%10; tmp/=10; a[p++]='0'+zz; } for(int i=0;i<p;i++) compute(i); cout<<sum; return 0; }附上别人的。思路一模一样,描述上更清晰。
#include<iostream> using namespace std; int main() { int N,sum,radix,index; cin >> N; sum = 0; radix = 1; do{ index = N/radix%10; if (index == 0)sum += N / (radix * 10)*radix; /*例如2032 当取到index=0时,此位为1时X1XX ,前面有01两种可能,后面有00~99radix=100种可能, PS:第一次做没有考虑到这种情况,借位有机会为1的情况*/ else if (index==1) sum += N / (radix * 10) *radix+N%radix + 1; /*例如24132,当取到1时,前面00~23种可能的时候,后面可以对应00~99radix=100种可能,而当取到24时,后面只有00~32=33种可能 PS:第一次做没有考虑到这种情况是只是最后一个的可能比较少*/ else if (index > 1)sum += (N / (radix * 10) + 1)*radix; /*例如4542,当取到5时,前面0~4五种可能的时候,后面对应00~99种可能*/ radix *= 10; } while (N / radix!=0); cout << sum<<endl; system("pause"); return 0; }
相关文章推荐
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- pat 甲级 1049. Counting Ones (30)
- PAT甲级 1049. Counting Ones (30)
- PAT_A 1049. Counting Ones (30)
- pat 1049. Counting Ones (30)
- pat甲1049. Counting Ones (30)
- Python实现Pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT甲级.1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT 甲级 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)(计算1到N,这些数字中1出现的个数,before i after,归纳)
- pat 1049. Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30)
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- PAT 1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)