题解 | #字符串加解密#
字符串加解密
http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
const plain = readline().split(''); // 明文
const cypher = readline().split(''); // 密文
/**
加密函数
*/
function encryption(p) {
const letterReg = /[a-z]/i;
if (letterReg.test(p)) {
// 是字母
const lowerA = 'a'.codePointAt();
const upperA = 'A'.codePointAt();
const lowerZ = 'z'.codePointAt();
const upperZ = 'Z'.codePointAt();
const pCp = p.codePointAt();
if (pCp < lowerA) {
// 大写字母
if (pCp === upperZ) {
// p 是大写'Z'
return 'a';
}
// p是大写'A'~'Y'
const next = String.fromCodePoint(pCp + 1);
return next.toLowerCase();
}
if (pCp === lowerZ) {
// p 是 小写'z'
return 'A';
}
// p 是小写'a'~'y'
const next = String.fromCodePoint(pCp + 1);
return next.toUpperCase();
} else if (!Number.isNaN(Number(p))) {
// 是数字
const n = Number(p);
if (n === 9) {
return 0;
}
return n + 1;
}
return '';
}
// 解密函数
function decryption(p) {
const letterReg = /[a-z]/i;
if (letterReg.test(p)) {
// 是字母
const lowerA = 'a'.codePointAt();
const upperA = 'A'.codePointAt();
const lowerZ = 'z'.codePointAt();
const upperZ = 'Z'.codePointAt();
const pCp = p.codePointAt();
if (pCp < lowerA) {
// 大写字母
if (pCp === upperA) {
// p 是大写'A'
return 'z';
}
// p是大写'B'~'Z'
const next = String.fromCodePoint(pCp - 1);
return next.toLowerCase();
}
if (pCp === lowerA) {
// p 是 小写'a'
return 'Z';
}
// p 是小写'b'~'z'
const next = String.fromCodePoint(pCp - 1);
return next.toUpperCase();
} else if (!Number.isNaN(Number(p))) {
// 是数字
const n = Number(p);
if (n === 0) {
return 9;
}
return n - 1;
}
return '';
}
const plainRes = plain.map(p => encryption(p));
console.log(plainRes.join(''));
const cypherRes = cypher.map(p => decryption(p));
console.log(cypherRes.join(''));

