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出现的次数。
#include<iostream>
#include<string>
#include<sstream>
#include<math.h>
using namespace std;
int CountOne(std::string num)
{
int len = num.length();
if(len == )
return ;
int fir = num[] - ''; if(len == && fir == )
return ;
if (len == && fir >= )
return ; int num1 = ,num2,num3;
if (fir == )
{
string re = num ,tem;
num.erase(num.begin());
tem = num;
num = re;
re = tem;
stringstream ss;
ss << re;
ss >> num1;
++ num1;
}
else if(fir > )
{
num1 = pow((double),len - );
}
num2 = (len -) * fir * pow((double),len-);
string tnum = num;
tnum.erase(tnum.begin());
num3 = CountOne(tnum);
return num1 + num2 + num3;
}
int main()
{
string num;
cin >> num;
printf("%d\n",CountOne(num));
return ;
}