题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; //方法一:利用ASCII码循环加解密,fromCharCode以及charCodeAt的使用 void async function () { const plainText = await readline(); const cipherText = await readline(); //加密 const encode = (plainText) => { let cipherText = ""; for(const c of plainText){ if(c>="a"&&c<="z") cipherText += String.fromCharCode("a".charCodeAt()+(c.charCodeAt()-"a".charCodeAt()+1)%26-32); else if(c>="A"&&c<="Z") cipherText += String.fromCharCode("A".charCodeAt()+(c.charCodeAt()-"A".charCodeAt()+1)%26+32); else if(c>="0"&&c<="9") cipherText += String.fromCharCode("0".charCodeAt() + (c.charCodeAt()-"0".charCodeAt()+1)%10); } return cipherText; } //解密 const decode = (cipherText) => { let plainText = ""; for(const c of cipherText){ if(c>="a"&&c<="z") plainText += String.fromCharCode("z".charCodeAt()-("z".charCodeAt()-c.charCodeAt()+1)%26-32); else if(c>="A"&&c<="Z") plainText += String.fromCharCode("Z".charCodeAt()-("Z".charCodeAt()-c.charCodeAt()+1)%26+32); else if(c>="0"&&c<="9") plainText += String.fromCharCode("9".charCodeAt()-("9".charCodeAt()-c.charCodeAt()+1)%10); } return plainText; } console.log(encode(plainText)); console.log(decode(cipherText)); }() // 方法二:利用map的方式 void (async function () { const decodeMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const encodeMap = "1234567890BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"; const plainText = await readline(); const cipherText = await readline(); const encode = (plainText) => { let cipherText = ""; for (const c of plainText) { cipherText += encodeMap[decodeMap.indexOf(c)]; } return cipherText; }; const decode = (cipherText) => { let plainText = ""; for (const c of cipherText) { plainText += decodeMap[encodeMap.indexOf(c)]; } return plainText; }; console.log(encode(plainText)); console.log(decode(cipherText)); })();