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

PAT 1049. Counting Ones (30)

时间:2015-08-21 23:05:15      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

1049. Counting Ones (30)

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 <iostream>
 2 #include <cmath>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 int ToInt(string num)
 8 {
 9     int res = 0;
10     for (int i = 0; i < num.size(); i++)
11         res = res * 10 + num[i] - 0;
12     return res;
13 }
14 
15 int CountingOnes(string num)
16 {
17     if (num.size() == 1)
18     {
19         if (num == "0")
20             return 0;
21         else
22             return 1;
23     }
24     else
25     {
26         int total = 0;
27         int first = num[0] - 0;
28         string sub = string(num.begin() + 1, num.end());
29         if (first == 1)
30             total += (ToInt(sub) + 1);
31         else if (first > 1)
32             total += pow(10, sub.size());
33         total += CountingOnes(sub) + first * CountingOnes(string(sub.size(), 9));
34         return total;
35     }
36 }
37 
38 int main()
39 {
40     string num;
41     cin >> num;
42 
43     cout << CountingOnes(num);
44 }

 

PAT 1049. Counting Ones (30)

标签:

原文地址:http://www.cnblogs.com/jackwang822/p/4749176.html

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