CF153C Caesar Cipher 的题解
洛谷传送门
CF传送门
题目大意
输入一个由大写字母构成的字符串 s s s ,求 s s s 的每一个字母往后移 k k k 位的结果。当字母移动后超出 Z \texttt{Z} Z 时,回到字母表的开头 A \texttt{A} A 继续移动。
思路
利用 ASCII 码。
ASCII (( American Standard Code for Information Interchange ): 美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言。它是最通用的信息交换标准,并等同于国际标准 ISO/IEC 646 。 ASCII 第一次以规范标准的类型发表是在 1967 年,最后一次更新则是在 1986 年,到目前为止共定义了 128 128 128 个字符 。
先计算字符串长度,然后取出每一位字母,最后将取出的字母移动 k k k 位。然后再判断加上 k k k 位后是否大于 Z \texttt{Z} Z,如果大于 Z \texttt{Z} Z 就减去 26 26 26。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <climits>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <ctime>
#include <string>
#include <cstring>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int main() {
int k;
string s;
cin >> s >> k;
int length = s.size(); // 计算字符串长度
for (int i = 0; i < length; i ++) { // 一定要从 0 开始
s[i] += k; // 向后移动 k 位
if (s[i] > 'Z') { // 如果大于 Z 就减去 26
s[i] -= 26;
}
}
cout << s;
return 0;
}
文章介绍了CF153C问题,即CaesarCipher加密方法。该问题要求对输入的全大写字母字符串按指定位数进行字母移位,超过Z则回绕到A。解决方案是利用ASCII码,遍历字符串并逐个字母移位,若超过Z则减去26。给出了C++的代码实现。
3382

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



