pat1049. Counting Ones (30)

1049. Counting Ones (30)

时间限制
10 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的贡献。

对于k位(k>=1):

1.Ak=0,count+=AnAn-1....Ak+1AkAk-1....A1*10^(k-1)

2.Ak=1,count+=AnAn-1....Ak+1AkAk-1....A1*10^(k-1)+Ak-1Ak-2...A1+1

3.Ak>=2,count+=(AnAn-1....Ak+1AkAk-1....A1+1)*10^(k-1)

 1 #include<cstdio>
 2 #include<stack>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<stack>
 6 #include<set>
 7 #include<map>
 8 using namespace std;
 9 //count的最大值是1036019223
10 int main(){
11     int n;
12     scanf("%d",&n);
13     long long base=1;
14     long long count=0;
15     int frpart,afpart,a;
16     while(n>=base){
17         a=n/base%10;
18         frpart=n/(10*base);
19         afpart=n%base;
20         count+=frpart*base;
21         if(a==1){
22             count+=afpart+1;
23         }
24         else if(a>1){
25             count+=base;
26         }
27         base*=10;
28     }
29     printf("%lld\n",count);
30     return 0;
31 }

 

posted @ 2015-09-01 19:41  Deribs4  阅读(295)  评论(0编辑  收藏  举报