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

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

时间:2016-01-25 22:57:11      阅读:491      评论: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



题目描述

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

 

 

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

标签:

原文地址:http://www.cnblogs.com/xiaoyesoso/p/5158761.html

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