原题地址:https://www.patest.cn/contests/pat-a-practise/1049
题目原文:
- Counting Ones (30) 时间限制 10 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue 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
本来是用树状数组来写的,有两个点会超时,后来用写出来的程序测试了一些数据,发现结果存在一些递归规律。
以212为例,212其实就是将0~99数两遍,再从0数到12,这三遍的不同之处在于,第二遍里的首位是1,也就是说,第二遍数出来的结果要加上数的数的个数。现在的问题变成了数0~99, 0~12,通过数据测试发现,0~9, 0~99, 0~999……的1的个数分别问1, 20, 300……存在明显的规律,事先计算出存在数据中,现在问题变成了数0~2,数个位数时,若该数大于等于1,返回1,否则为0.
下面是AC的代码
#include<cstdio>
#include<sstream>
#include<string>
#include<vector>
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
int lee[15]; //用于存储事先计算好的数据,lee[i]表示从0数到10*i - 1所含的1
int mpow(int cur)
{
int res = 1;
for (int i = 0; i < cur; i ++)
{
res *= 10;
}
return res;
}
int han(const string& cur)
{
if(cur.size() == 0)
return 0;
else if(cur.size() == 1)
{
if(cur[0] >= '1')
return 1;
else
return 0;
}
stringstream ss;
int res = lee[cur.size() - 1];
int n = atoi(cur.substr(1, cur.size() - 1).c_str());
ss << n;
if(cur[0] > '1')
{
return mpow(cur.size() - 1) + res * (cur[0] - '0') + han(ss.str());
}else if(cur[0] == '1'){
return res * (cur[0] - '0') + han(ss.str()) + n + 1;
}
}
int main()
{
string sn;
cin >> sn;
for (int i = 1; i < 15; i ++)
lee[i] = i * mpow(i - 1);
int res = han(sn);
cout << res << endl;
return 0;
}