题解 | 字符串加解密
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
//是有点长啊,但是思路好理解,比较直接
#include <iostream>
using namespace std;
// 加密函数
string encrypt(const string& text) {
string result = "";
for (char c : text) {
if (c >= 'A' && c < 'Z') {
// A-Y 转换为小写 b-z
c = c + 1;
c = c + 32;
result += c;
}
else if (c >= 'a' && c < 'z') {
// a-y 转换为大写 B-Z
c = c + 1;
c = c - 32;
result += c;
}
else if (c == 'Z') {
// Z 转换为 a
c = 'a';
result += c;
}
else if (c == 'z') {
// z 转换为 A
c = 'A';
result += c;
}
else if (c >= '0' && c < '9') {
// 0-8 转换为 1-9
c = c + 1;
result += c;
}
else if (c == '9') {
// 9 转换为 0
c = '0';
result += c;
}
else {
// 其他字符保持不变
result += c;
}
}
return result;
}
// 解密函数(与加密规则相反)
string decrypt(const string& text) {
string result = "";
for (char c : text) {
if (c >= 'b' && c <= 'z') {
// 小写 b-z 转换为大写 A-Y
c = c - 1;
c = c - 32;
result += c;
}
else if (c >= 'B' && c <= 'Z') {
// 大写 B-Z 转换为小写 a-y
c = c - 1;
c = c + 32;
result += c;
}
else if (c == 'a') {
// a 转换为 Z
c = 'Z';
result += c;
}
else if (c == 'A') {
// A 转换为 z
c = 'z';
result += c;
}
else if (c >= '1' && c <= '9') {
// 1-9 转换为 0-8
c = c - 1;
result += c;
}
else if (c == '0') {
// 0 转换为 9
c = '9';
result += c;
}
else {
// 其他字符保持不变
result += c;
}
}
return result;
}
int main() {
string s, t;
getline(cin, s);
getline(cin, t);
string encrypted = encrypt(s);
string decrypted = decrypt(t);
cout << encrypted << endl;
cout << decrypted << endl;
return 0;
}
// 64 位输出请用 printf("%lld")
