您的位置:首页 > 其它

PAT 1049. Counting Ones (30)

2015-08-21 22:25 429 查看

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


#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int ToInt(string num)
{
int res = 0;
for (int i = 0; i < num.size(); i++)
res = res * 10 + num[i] - '0';
return res;
}

int CountingOnes(string num)
{
if (num.size() == 1)
{
if (num == "0")
return 0;
else
return 1;
}
else
{
int total = 0;
int first = num[0] - '0';
string sub = string(num.begin() + 1, num.end());
if (first == 1)
total += (ToInt(sub) + 1);
else if (first > 1)
total += pow(10, sub.size());
total += CountingOnes(sub) + first * CountingOnes(string(sub.size(), '9'));
return total;
}
}

int main()
{
string num;
cin >> num;

cout << CountingOnes(num);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: