标签:
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 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