题解
2024-11-09 16:42:22
发布于:广东
6阅读
0回复
0点赞
第一种方法
循环遍历每一个数字再统计
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
while (cin >> a >> b)
{
if (a==0 && b==0) return 0;
if (a>b) swap(a,b);
int s[10]={0};
for (;a<=b;a++)
{
int _=a;
while (_>0)
{
s[_%10]++;
_/=10;
}
}
for (int i=0;i<=9;i++)
cout << s[i] << ' ';
cout << endl;
}
}
第二种方法
先用一个字符串把a~b的所有数字加进去,然后用count函数计算0~9的个数
count函数的原型如下:
template <class InputIt, class T>
size_t count(InputIt first, InputIt last, const T& value);
传入两个迭代器和给定统计的值
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
while (cin >> a >> b)
{
if (a==0 && b==0)
return 0;
if (a>b)
swap(a,b);
string s="";
for (;a<=b;a++)
s+=to_string(a);
for (int i=0;i<=9;i++)
cout << count(s.begin(),s.end(),i+'0') << ' ';
cout << endl;
}
}
第三种方法
先计算0~n的数据,利用二维数组存储,设0~i中数字j的个数为,则有
其中n表示i中数字j的个数
然后利用算出a~b中数字0~9的个数
但是这种方法耗时间
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
int s[1000001][10];
for (int i=0;i<=9;i++)
s[1][i]=0;
s[1][1]=1;
for (int i=2;i<=100000;i++)
{
for (int j=0;j<=9;j++)
s[i][j]=s[i-1][j]+count(to_string(i).begin(),to_string(i).end(),j+'0');
}
while (cin >> a >> b)
{
if (a==0 && b==0)
return 0;
if (a>b)
swap(a,b);
for (int i=0;i<=9;i++)
cout << ceil((s[b][i]-s[a-1][i])/2.0) << ' ';
cout << endl;
}
}
这里空空如也
有帮助,赞一个