题解 | #字符串加解密# JS Node一楼进行了一些小改

字符串加解密

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;
const 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 (const i in arr) {
        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();
        }
    }
    return arr.join("");
}

function decryption(str) {
    const arr = str.split("");
    for (const i in arr) {
        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();
        }
    }
    return arr.join("");
}

全部评论

相关推荐

头像
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务