今天刷基础题时,用到了count()函数,个人觉得很方便,但刚开始时对这个函数用错了,导致结果一直不对,写一下我的错误
先看题目:
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
小蓝有很多数字卡片,每张卡片上都是数字 00 到 99。 小蓝准备用这些卡片来拼一些数,他想从 11 开始拼出正整数,每拼一个, 就保存起来,卡片就不能用来拼其它数了。 小蓝想知道自己能从 11 拼到多少。 例如,当小蓝有 3030 张卡片,其中 00 到 99 各 33 张,则小蓝可以拼出 11 到 1010, 但是拼 1111 时卡片 11 已经只有一张了,不够拼出 1111。 现在小蓝手里有 00 到 99 的卡片各 20212021 张,共 2021020210 张,请问小蓝可以从 11 拼到多少? 提示:建议使用计算机编程解决问题
错误代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a10=0,ant=0;
for(int i=1; ; i++)
{
s=to_string(i);
for(int j=1; j<=s.length(); j++) //这里不对!!!
{
a1+=count(s.begin(),s.end(),'0');
a2+=count(s.begin(),s.end(),'1');
a3+=count(s.begin(),s.end(),'2');
a4+=count(s.begin(),s.end(),'3');
a5+=count(s.begin(),s.end(),'4');
a6+=count(s.begin(),s.end(),'5');
a7+=count(s.begin(),s.end(),'6');
a8+=count(s.begin(),s.end(),'7');
a9+=count(s.begin(),s.end(),'8');
a10+=count(s.begin(),s.end(),'9');
if(a1>2021||a2>2021||a3>2021||a4>2021||a5>2021||a6>2021||a7>2021||a8>2021||a9>2021||a10>2021)
{
cout<<i-1;
return 0;
}
}
}
return 0;
}
这里for循环不对,count()函数本来就是遍历字符串查找指定字符的个数,若再用循环遍历查找,则查了两遍,那么得出来的个数必定是不对的,所以用了count()函数后不用再用循环了!!!
正确代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a10=0,ant=0;
for(int i=1; ; i++)
{
s=to_string(i); //将i转换为字符串
//分别查找各个数字的个数
a1+=count(s.begin(),s.end(),'0');
a2+=count(s.begin(),s.end(),'1');
a3+=count(s.begin(),s.end(),'2');
a4+=count(s.begin(),s.end(),'3');
a5+=count(s.begin(),s.end(),'4');
a6+=count(s.begin(),s.end(),'5');
a7+=count(s.begin(),s.end(),'6');
a8+=count(s.begin(),s.end(),'7');
a9+=count(s.begin(),s.end(),'8');
a10+=count(s.begin(),s.end(),'9');
if(a1>2021||a2>2021||a3>2021||a4>2021||a5>2021||a6>2021||a7>2021||a8>2021||a9>2021||a10>2021)
{
cout<<i-1; //此时i已有卡片不足,不能拼到i,需要-1,易错!!!!!
return 0; //当某一数字大于2021时,即卡片不够,则结束循环,输出
}
}
return 0;
}