今天是【蓝桥杯】枚举2的6道真题归纳。
一、卡片
2021年A组A题,B组B题。
题目描述
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
小蓝有很多数字卡片,每张卡片上都是数字 0 到 9。
小蓝准备用这些卡片来拼一些数,他想从 1 开始拼出正整数,每拼一个,就保存起来,卡片就不能用来拼其它数了。
小蓝想知道自己能从 1 拼到多少。
例如,当小蓝有 30 张卡片,其中 0 到 9 各 3 张,则小蓝可以拼出 1 到 10,
但是拼 1 时卡片 1 已经只有一张了,不够拼出 11。
现在小蓝手里有 0 到 9 的卡片各 2021 张,共 20210 张,请问小蓝可以从 1 拼到多少?
提示:建议使用计算机编程解决问题。
这题体现了while的优势,当不知道要枚举多大数据时,可以先写个while,找到之后跳出循环就可。要注意的是,while(n)后面如果想继续使用n的话,需要一个临时变量。
这题要注意一个点:1肯定是先用完的。
我们要找的答案是最多可以拼多少个。
即n一定包含1,答案是n-1。
方法一:我的代码
#include<iostream>
using namespace std;
int nums[10];
int main(void)
{
for(int i = 0; i <= 9; i++)
nums[i] = 2021;
int n = 1;
while(1)
{
int res = n;
for(int i = 0; res; i++)
{
nums[res % 10]--;
res /= 10;
}
for(int i = 0; i <= 9; i++)
if(nums[i] < 0)
{
cout<< n-1 << endl;
return 0;
}
n++;
}
return 0;
}
方法二:带练学长的代码
#include<iostream>
using namespace std;
int main(void)
{
int cnt[10];
for(int i = 0; i <= 9; i++)
cnt[i] = 2021;
int n = 1;
while(true)
{
int res = n;
while(res)
{
cnt[res % 10]--;
if(cnt[res % 10] < 0)
{
cout<< n-1 << endl;
return 0;
}
res /= 10;
}
n++;
}
return 0;
}
方法三:老师的代码
#include<iostream>
using namespace std;
int main(void)
{
int cnt[10];
for(int i = 0; i <= 9; i++)
cnt[i] = 2021;
int n = 1;
while(true)
{
int res = n;
while(res)
{
int now = res % 10;
if