题目:来源于洛谷
分析:
题目要我们求出两个整数(包括这两个整数在内)之间的数中,从0到9每个数字出现的次数。
我想到的是用字符流接收输入进来的数,然后定义一个字符串取字符流中的数据,最后利用count函数统计字符串中每个字符出现的次数
下面要介绍一下解题需要用到的东西:
- stringstream是字符流,用于接收数字,使用它需要加头文件 sstream;但是字符流是不能直接输出的,需要用到stringstream类的成员函数str() 才能把它当作普通字符串来用,例如:string s = ss.str();
- count是用统计某一给定值出现的次数,count ( ivec.begin(), ivec.end(), value) ,前两个参数是迭代器,第3个参数是要统计的值。可以把它理解为统计给定的值 在一个数组的首位到末位 出现的次数。当然,使用count函数也需要包含头文件 < algorithm >
上代码吧!!!
#include <iostream>
#include <cstdio>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int m, n;
cin >> m >> n;
stringstream ss;
for (int i = m; i <= n; ++i) {
ss << i;
}
string s = ss.str();
for (int i = 0; i < 10; ++i) {
cout << count(s.begin(), s.end(), i+'0');
if (i != 9) {
cout << " ";
}
}
return 0;
}
再刷两题,我就去转战LC了o( ̄▽ ̄)o