【中等】算法nodeJs:字符串加解密

131 阅读1分钟

描述

规定这样一种密码的加密方法:
∙对于密码中的英文字母,按照字母表顺序,向后移动一位,同时改变大小写,即 Z 转换为 a ,A 转换为 b ,B 转换为 c ,⋯ ,Y 转换为 z ,Z 转换为 a 。
∙对于密码中的数字,增加 1 ,9 转换为 0 。
字符串的解密方法即为加密方法的逆过程。

现在,对于给定的明文字符串 s ,将其加密;对于给定的密文字符串 t ,将其解密。

输入描述:

第一行输入一个长度为 1≦length(s)≦103 的字符串 s ,代表给定的明文字符串;
第二行输入一个长度为 1≦length(t)≦103 的字符串 t ,代表给定的密文字符串。

除此之外,保证字符串 s 和 t 中仅包含英文字母和数字。

输出描述:

第一行输出一个字符串,代表加密后的 s 。
第二行输出一个字符串,代表解密后的 t 。

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    const arr = [];
    while ((line = await readline())) {
        arr.push(line);
    }
    let [s, t] = arr;
    let s_ = "",
        t_ = "";
    for (let i = 0; i < s.length; i++) {
        if (/[a-z]/.test(s[i])) {
            if (s[i] == "z") s_ += "A";
            else s_ += String.fromCharCode(s[i].toUpperCase().charCodeAt() + 1);
        } else if (/[A-Z]/.test(s[i])) {
            if (s[i] == "Z") s_ += "a";
            else s_ += String.fromCharCode(s[i].toLowerCase().charCodeAt() + 1);
        } else if (/[0-9]/.test(s[i])) {
            if (s[i] == "9") s_ += "0";
            else s_ += String.fromCharCode(s[i].charCodeAt() + 1);
        }
    }
    console.log(s_);
    for (let i = 0; i < t.length; i++) {
        if (/[a-z]/.test(t[i])) {
            if (t[i] == "a") t_ += "Z";
            else t_ += String.fromCharCode(t[i].toUpperCase().charCodeAt() - 1);
        } else if (/[A-Z]/.test(t[i])) {
            if (t[i] == "A") t_ += "z";
            else t_ += String.fromCharCode(t[i].toLowerCase().charCodeAt() - 1);
        } else if (/[0-9]/.test(t[i])) {
            if (t[i] == "0") t_ += "9";
            else t_ += String.fromCharCode(t[i].charCodeAt() - 1);
        }
    }
    console.log(t_);
})();