HJ29. 字符串加解密
描述
对输入的字符串进行加解密,并输出。
加密方法为:
当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;
当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;
其他字符不做变化。
输入描述
第一行输入一串要加密的密码
第二行输入一串加过密的密码
输出描述
第一行输出加密后的字符
第二行输出解密后的字符
示例1
输入:
abcdefg BCDEFGH
输出:
BCDEFGH abcdefg
C 解法, 执行用时: 1ms, 内存消耗: 276KB, 提交时间: 2020-10-15
#include <stdio.h> #include <ctype.h> int main(void){ const int sz = 128; char ENC[128]; char DEC[128]; char enc[sz], dec[sz]; char *p; int i; ENC['9'] = '0'; ENC['Z'] = 'a'; ENC['z'] = 'A'; for(i = 0; i < sz; ++i){ if(i == '9' || i == 'z' || i == 'Z') continue; else if(isdigit(i)) ENC[i] = i + 1; else if(islower(i)) ENC[i] = toupper(i + 1); else if(isupper(i)) ENC[i] = tolower(i + 1); else ENC[i] = i; } DEC['0'] = '9'; DEC['A'] = 'z'; DEC['a'] = 'Z'; for(i = 0; i < sz; ++i){ if(i == '0' || i == 'A' || i == 'a') continue; if(isdigit(i)) DEC[i] = i - 1; else if(islower(i)) DEC[i] = toupper(i - 1); else if(isupper(i)) DEC[i] = tolower(i - 1); else DEC[i] = i; } while(scanf("%s\n%s\n", enc, dec) == 2){ for(p = enc; *p; ++p) *p = ENC[*p]; for(p = dec; *p; ++p) *p = DEC[*p]; printf("%s\n%s\n", enc, dec); } }
C 解法, 执行用时: 1ms, 内存消耗: 304KB, 提交时间: 2021-08-31
#include<stdio.h> #include<string.h> int main() { void Encrypt(char aucPassword[], char aucResult[]); void unEncrypt(char result[], char password[]); char password1[101]={},result2[101] = {}; while(gets(password1)) { gets(result2); char password2[101]={},result1[101] = {}; Encrypt(password1,result1); unEncrypt(result2,password2); } return 0; } void Encrypt(char aucPassword[], char aucResult[]) { int i; for(i=0;aucPassword[i]!='\0';i++) { if(aucPassword[i]>='a'&&aucPassword[i]<='y') { aucResult[i] = aucPassword[i]-31; } else if(aucPassword[i]=='z') { aucResult[i] = 'A'; } else if(aucPassword[i]>='A'&&aucPassword[i]<='Y') { aucResult[i] = aucPassword[i]+33; } else if(aucPassword[i]=='Z') { aucResult[i] = 'a'; } else if(aucPassword[i]>='0'&&aucPassword[i]<='8') { aucResult[i] = aucPassword[i]+1; } else if(aucPassword[i]=='9') { aucResult[i] = '0'; } else { aucResult[i] = aucPassword[i]; } } puts(aucResult); } void unEncrypt(char result[], char password[]) { int i; for(i=0;result[i]!='\0';i++) { if(result[i]>='b'&&result[i]<='z') { password[i] = result[i]-33; } else if(result[i]=='a') { password[i] = 'Z'; } else if(result[i]>='B'&&result[i]<='Z') { password[i] = result[i]+31; } else if(result[i]=='A') { password[i] = 'z'; } else if(result[i]>='1'&&result[i]<='9') { password[i] = result[i]-1; } else if(result[i]=='0') { password[i] = '9'; } else { password[i] = result[i]; } } puts(password); }