问题描述
一本书的页码从自然数 1 开始顺序编码直到自然数 n。书的页码按照通常的习惯编排,每个页码都不含多余的前导数字 0。例如,第 6 页用数字 6 表示而不是 06 或 006 等。数字计数问题要求对给定书的总页码 n,计算书的全部页码分别用到多少次数字 0,1,2,…,9。
算法设计
给定表示书的总页码的十进制整数 n ( 1 ≤ n ≤ 1 0 9 ) (1\le n\le 10^9) (1≤n≤109),计算书的全部页码中分别用到多少次数字0,1,2,…,9。
数据输入
输入数据由文件名为 input.txt 的文本文件提供。每个文件只有 1 行,给出表示书的总页码的整数 n。
结果输出
将计算结果输出到文件 output.txt。输出文件共 10 行,在第 k(k=1,2,…,10)行输出页码中用到数字 k-1 的次数。
输入文件示例
input.txt
11
输出文件示例
output.txt
1
4
1
1
1
1
1
1
1
1
代码实现(C++)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool statistics(int page,int* result)
{
if(page <= 0)
return false;
string temp;
for(int i=0;i<10;++i)
result[i] = 0;
for(int i=1;i<=page;++i)
{
temp = to_string(i);
for(int j=0;j<temp.length();++j)
{
++(result[temp[j]-'0']);
}
}
return true;
}
int main()
{
ifstream in("input.txt",ios::in);
ofstream out("output.txt",ios::out);
if(!in)
{
cerr<<"File could not be opened"<<endl;
exit(EXIT_FAILURE);
}
if(!out)
{
cerr<<"File could not be opened"<<endl;
exit(EXIT_FAILURE);
}
int page;
int result[10];
in>>page;
in.close();
statistics(page,result);
for(int i=0;i<9;++i)
out<<result[i]<<endl;
out<<result[9];
out.close();
return 0;
}