欢乐赛#36 题解
2024-12-22 22:03:38
发布于:江苏
第一题
思路
直接用<cmath>中的abs函数求绝对值即可,或者用 的减法,取绝对值。
代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
cout << abs(n); // cout << 0-n;
return 0;
}
第二题
思路
要求4和6的倍数,其实也就是4和6的最小公倍数即12,所以直接判断是否是12的倍数即可。
代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
if (n % 12 == 0)
cout << "YES";
else
cout << "NO";
return 0;
}
第三题
思路
需要求当前值加上自己的下标即可,这里面不需要用数组存储,直接边输入边输出即可。
代码
#include <bits/stdc++.h>
using namespace std;
int n, x;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> x;
cout << x + i << " ";
}
return 0;
}
第四题
思路
遍历当前字符串,如果字符串下标是奇数,则输出 ,否则输出 ,由于题目中下标是从1开始数的,正常字符串是从0开始数的,所以需要变成为偶数下标时,输出则输出
代码
#include <bits/stdc++.h>
using namespace std;
int n;
string s1, s2;
int main()
{
cin >> n >> s1 >> s2;
for (int i = 0; i < n; i++)
{
if (i & 1) // 如果当前下标是奇数,则输出s1[i]
cout << s1[i];
else
cout << s2[i];
}
return 0;
}
第五题
思路
题目中:“「边缘元素」的定义: 假设 是边缘元素只要满足 或者 或者 或者 。”
将上面的条件翻译成代码即可。
代码
#include <bits/stdc++.h>
using namespace std;
int n, x, sum; // sum用来存储边缘元素的和
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> x;
if (i == 1 || j == 1 || i == n || j == n)
sum += x;
}
}
cout << sum;
return 0;
}
第六题
思路
考察最大公约数的求法,这里使用辗转相除法。
代码
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
return b ? gcd(b, a % b) : a;
}
int t, x, y, a, b;
int main()
{
cin >> t;
while (t--)
{
cin >> x >> y >> a >> b;
cout << gcd(gcd(x, y), gcd(a, b)) << "\n";
}
return 0;
}
这里空空如也
有帮助,赞一个