1、输入一个字母(大写或者小写),和一个整数n,输出一个‘Z’字型。如果输出过程中到达z或Z,要从a或A继续输出,即实现循环。
例如
示例一:
输入c 4 (‘z’字型的高度和宽度都是n)
输出如下:
示例二:
输入:Y 7
输出如下:
代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char ch;
cin >> ch;
int n;
cin >> n;
for (int j = 0; j < n; j++) {
cout << ch++;
if (ch > 'z' || ch == 'Z'+1) ch -= 26;
}
cout << endl;
for (int i = 1, j = n-2; i < n-1; i++, j--) {
for (int k = 0; k < j; k++)
cout << ' ';
cout << ch++;
if (ch > 'z' || ch == 'Z'+1) ch -= 26;
cout << endl;
}
for (int i = n-1, j = 0; j < n; j++) {
cout << ch++;
if (ch > 'z' || ch == 'Z'+1) ch -= 26;
}
cout << endl;
return 0;
}
2、输入一组单词(区分大小写),统计首字母相同的单词的个数,相同的单词不累加,输出格式:“字母,个数”,语句中的标点只有逗号 句号
input: I am a boy,you are a boy.
output:
I,1
a,3
b,1
y,1
代码:
#include <bits/stdc++.h>
using namespace std;
vector<int> nums; // 存数
int main()
{
string s;
getline(cin, s);
// 分解单词
vector<string> ans;
int i = 0;
while (i < s.size()) {
for (int j = i; j <= s.size(); j++) {
if (s[j] == ' ' || s[j] == ',' || s[j] == '.') {
ans.push_back(s.substr(i, j-i));
i = j+1;
break;
}
}
}
for (string i : ans) {
cout << i << endl;
}
set<string> se;
for (string i : ans) {
se.insert(i);
}
map<char,int> m;
for (auto i : se) {
m[i[0]]++;
}
for (auto it : m) {
cout << it.first << ',' << it.second << endl;
}
}
3、输入日期,实现加5天的操作。
输入: 3个用空格隔开的整数,分别表示年、月、日。要考虑闰年
输出: 输入加完后的天数
示例1:
输入:2025 3 25
输出:2025-3-30
示例2:
输入:2024 12 31
输出:2025-1-5
示例3:
输入:2024 2 27
输出:2024-3-3
代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int y, m, d;
cin >> y >> m >> d;
switch(m) {
case 12:
case 10:
case 8:
case 7:
case 5:
case 3:
case 1:
if (d+5 > 31) {
d = d+5-31;
m++;
if (m > 12) {
y++;
m=1;
}
}else {
d=d+5;
}
break;
case 11:
case 9:
case 6:
case 4:
if (d+5 > 30) {
d = d+5-30;
m++;
}else d=d+5;
break;
case 2:
if (y%400==0 || y%100!=0 && y%4==0)
{
if (d+5>29) {
d=d+5-29;
m++;
} else d=d+5;
} else {
if (d+5>28) {
d=d+5-28;
m++;
} else d=d+5;
}
}
cout << y << '-' << m <<'-' <<d;
}
4、轮转数组
输入一个数组nums,一个整数k,将数组中的元素向右轮转k个位置,其中k>=0
示例一:
输入:
1 2 3 4 5 6 7
3
输出:5 6 7 1 2 3 4
示例二:
输入:
-1 -100 3 99
2
输出:3 99 -1 -100
数据范围:
- 1 <= nums.length <= 105
- 0 <= k <= 105
注意,k可能超过数组长度!
例如:
输入:
1 2 3 4
7
输出:2 3 4 1
代码:
#include <bits/stdc++.h>
using namespace std;
vector<int> nums; // 存数
// 版本一
int main()
{
vector<int> ans;
int x;
while (cin >> x) {
ans.push_back(x);
if(getchar() =='\n') {
break;
}
}
int k;
cin >> k;
while (k--) {
ans.insert(ans.begin(), ans.back());
ans.pop_back();
}
for (int i : ans) {
cout << i << ' ';
}
}
// 版本二:版本二的时间复杂度要比版本一低。
int main()
{
vector<int> nums;
int x;
while (cin >> x) {
nums.push_back(x);
if(getchar() =='\n') {
break;
}
}
int k;
cin >> k;
int n = nums.size();
k %= n;
vector<int> ans; // 存储答案
// 旋转部分是[n-k,n) 先加入结果ans中;之后再加入前面的[0,n-k)
for (int i = n-k; i < n; i++) ans.push_back(nums[i]);
for (int i = 0; i < n-k; i++) ans.push_back(nums[i]);
for (int i = 0; i < n; i++) cout << ans[i] << ' ';
return 0;
}