代码开源在GitHub上,持续在此更新题解。
2007题注意输入的两组数据前后大小关系,一定要保持前一个数字小于第二个数字
2024/2/19
此次更新2010~2019题
着重注意2017,2018两题。
// Problem Description(2017)
// 对于给定的一个字符串,统计其中数字字符出现的次数。
// Input
// 输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。
// Output
// 对于每个测试实例,输出该串中数值的个数,每个输出占一行。
// Sample Input
// 2
// asdfasdf123123asdfasdf
// asdf111111111asdfasdfasdf
// Sample Output
// 6
// 9
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cin>>n;
cin.ignore();
while (n--) {
char str[1000];
cin.getline(str, 1000);
int count = 0;
for (int i = 0; i < strlen(str); i++)
{
if (str[i]>='0'&&str[i]<='9')
{
count++;
}
}
cout << count << endl;
}
return 0;
}
这段代码若去掉cin.ignore()则会出现问题
问题出在使用 cin >> n 读取 n 的时候,输入缓冲区中的换行符没有被清除,导致第一个 getline() 读取了换行符而不是预期的字符串。
解决这个问题的方法之一是在读取 n 之后使用 cin.ignore() 来清除输入缓冲区中的换行符,或者直接使用 getline() 来读取 n。另外,也可以在读取字符串之前使用 cin.ignore() 来清除换行符。
// Problem Description
// 有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
// Input
// 输入数据由多个测试实例组成,每个测试实例占一行,包括一个整数n(0<n<55),n的含义如题目中描述。
// n=0表示输入数据的结束,不做处理。
// Output
// 对于每个测试实例,输出在第n年的时候母牛的数量。
// 每个输出占一行。
// Sample Input
// 2
// 4
// 5
// 0
// Sample Output
// 2
// 4
// 6
#include <iostream>
using namespace std;
int main()
{
int cows[55] = {
0, 1, 2, 3, 4};
for (int i = 5; i < 55; i++)
{
cows[i] = cows[i - 1] + cows[i - 3];
}
int n;
while (cin >> n && n != 0)
{
cout << cows[n] << endl;
}
return 0;
}
这个问题为一个数学问题,在求解时可定义一个数组,采用递归的方式求出后续数组中数据的大小。类似斐波那契数列求解。
2024/2/23
Problem Description
输入一个字符串,判断其是否是C的合法标识符。
Input
输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。
Output
对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出"yes",否则,输出“no”。
Sample Input
3
12ajf
fi8x_a
ff ai_2
Sample Output
no
yes
no
这道题有一定坑。
以下为正确代码。
#include <iostream>
using namespace std;
bool isValidIdentifier(const char* str)
{
if (!((str[0] >= 'a' && str[0] <= 'z') || (str[0] >= 'A' && str[0] <= 'Z') || str[0] == '_'))
{
return false;
}
for (int i = 1; str[i] != '\0'; ++i)
{
if (!((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9') || str[i] == '_'))
{
return false;
}
}
return true;
}
int main()
{
int n;
cin >> n;
cin<

最低0.47元/天 解锁文章
959

被折叠的 条评论
为什么被折叠?



