标签:
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:12Sample 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 }
标签:
原文地址:http://www.cnblogs.com/jackwang822/p/4749176.html