1049. Counting Ones/整数中1出现的次数(从1到n整数中1出现的次数)

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~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
 
 1 #include<iostream>
 2 #include<string>
 3 #include<sstream>
 4 #include<math.h>
 5 using namespace std;
 6 int CountOne(std::string num)
 7 {
 8     int len = num.length();
 9     if(len == 0)
10         return 0;
11     int fir = num[0] - '0';
12 
13     if(len == 1 && fir == 0)
14         return 0;
15     if (len == 1 && fir >= 1)
16         return 1;
17 
18     int num1 = 0,num2,num3;
19     if (fir == 1)
20     {
21         string re = num ,tem;
22         num.erase(num.begin());
23         tem = num;
24         num = re;
25         re = tem;
26         stringstream ss;
27         ss << re;
28         ss >> num1;
29         ++ num1;
30     }
31     else if(fir > 1)
32     {
33         num1 = pow((double)10,len - 1);
34     }
35     num2 = (len -1) * fir * pow((double)10,len-2);
36     string tnum = num;
37     tnum.erase(tnum.begin());
38     num3 = CountOne(tnum);
39     return num1 + num2 + num3;
40 }
41 int main()
42 {
43     string num;
44     cin >> num;
45     printf("%d\n",CountOne(num));
46     return 0;
47 }

 

posted @ 2016-01-25 21:25  小爷  阅读(264)  评论(0编辑  收藏  举报