题解 | 字符串加解密
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
#include <iostream> #include <cctype> using namespace std; char alpha_trans(char c, bool decode) { char ans; if(isupper(c)) { int n = (c - 'A'); if(!decode) n = (n + 1) % 26; //加密 else n = (n + 25) % 26; //解密 ans = n + 'A'; ans = tolower(ans); } else { int n = (c - 'a'); if(!decode) n = (n + 1) % 26; //加密 else n = (n + 25) % 26; //解密 ans = n + 'a'; ans = toupper(ans); } return ans; } char num_trans(char c, bool decode) { int n = c - '0'; if(decode) { //解密 n = (n + 9) % 10; } else { //加密 n = (n + 1) % 10; } c = '0' + n; return c; } int main() { string s, t; cin >> s >> t; string encrypt, decode; for(const char& c: s) { //对s加密 if(isalpha(c)) { encrypt += alpha_trans(c, false); } else { encrypt += num_trans(c, false); } } for(const char& c: t) { //对t解密 if(isalpha(c)) { decode += alpha_trans(c, true); } else { decode += num_trans(c, true); } } cout << encrypt << endl; cout << decode << endl; return 0; }