HJ29 字符串加解密qaq

74 阅读1分钟

image.png

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
let lines = [];
void (async function () {
    // Write your code here
    while ((line = await readline())) {
        lines.push(line);
        if (lines.length == 2) {
            console.log(encryption(lines[0]));
            console.log(decryption(lines[1]));
        }
    }
})();

function encryption(str) {
    let arr = str.split("");
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].match(/[A-Z]/)) {
            arr[i] =
                arr[i] == "Z"
                    ? "a"
                    : String.fromCharCode(
                          arr[i].toLowerCase().charCodeAt(0) + 1
                      );
        } else if (arr[i].match(/[a-z]/)) {
            arr[i] =
                arr[i] == "z"
                    ? "A"
                    : String.fromCharCode(
                          arr[i].toUpperCase().charCodeAt(0) + 1
                      );
        } else if (arr[i].match(/[0-9]/)) {
            arr[i] = arr[i] == "9" ? "0" : (parseInt(arr[i]) + 1).toString();
        }
    }
    let res = arr.join("");
    return res;
}

function decryption(str) {
    let arr = str.split("");
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].match(/[A-Z]/)) {
            arr[i] =
                arr[i] == "A"
                    ? "z"
                    : String.fromCharCode(
                          arr[i].toLowerCase().charCodeAt(0) - 1
                      );
        } else if (arr[i].match(/[a-z]/)) {
            arr[i] =
                arr[i] == "a"
                    ? "Z"
                    : String.fromCharCode(
                          arr[i].toUpperCase().charCodeAt(0) - 1
                      );
        } else if (arr[i].match(/[0-9]/)) {
            arr[i] = arr[i] == "0" ? "9" : (parseInt(arr[i]) - 1).toString();
        }
    }
    let res = arr.join("");
    return res;
}

字符串加解密_牛客题霸_牛客网 (nowcoder.com)