码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1049. Counting Ones

时间:2015-02-20 11:53:35      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:本题思路很值得让人思考,一位一位的进行分析可使时间大为减少,另外需要注意的一点就是当分析的数字为0,为1和大于等于2的情况时应该仔细区分情况。
技术分享
 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 int main(int argc, char *argv[])
 5 {
 6     int N;
 7     scanf("%d",&N);
 8     int sum=0,left=10,right=1;
 9     int NN=N;
10     int pt;
11     int now=10;
12     while(NN!=0)
13     {
14         int temleft=N/left;
15         int temright=N%right;
16         pt=NN%10;
17         NN/=10;
18         if(pt==0)
19         {
20             sum+=temleft*right;
21         }
22         else if(pt==1)
23         {
24             sum+=temleft*right+temright+1; 
25         }
26         else
27         {
28             sum+=(temleft+1)*right;
29         }
30         left*=10;
31         right*=10;        
32     }
33     printf("%d\n",sum);
34     return 0;
35 }
View Code

 

PAT1049. Counting Ones

标签:

原文地址:http://www.cnblogs.com/GoFly/p/4296447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!