题解 | #字符串加解密#

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const lines: string[] = [];

rl.on("line", function (line: string) {
    lines.push(line);
});

rl.on("close", () => {
    console.log(encrypt(lines[0]));
    console.log(decrypt(lines[1]));
});

// 加密
const encrypt = (str: string): string => {
    const strs = str.split("");

    strs.forEach((item, index) => {
        if (/[0-9]/.test(item)) {
            strs[index] = item === "9" ? "0" : `${parseInt(item) + 1}`;
        }

        if (/[a-z]/.test(item)) {
            strs[index] =
                item === "z"
                    ? "A"
                    : String.fromCharCode(item.toUpperCase().charCodeAt(0) + 1);
        }

        if (/[A-Z]/.test(item)) {
            strs[index] =
                item === "Z"
                    ? "a"
                    : String.fromCharCode(item.toLowerCase().charCodeAt(0) + 1);
        }
    });

    return strs.join("");
};

// 解密
const decrypt = (str: string): string => {
    const strs = str.split("");

    strs.forEach((item, index) => {
        if (/[0-9]/.test(item)) {
            strs[index] = item === "0" ? "9" : `${parseInt(item) - 1}`;
        }

        if (/[a-z]/.test(item)) {
            strs[index] =
                item === "a"
                    ? "Z"
                    : String.fromCharCode(item.toUpperCase().charCodeAt(0) - 1);
        }

        if (/[A-Z]/.test(item)) {
            strs[index] =
                item === "A"
                    ? "z"
                    : String.fromCharCode(item.toLowerCase().charCodeAt(0) - 1);
        }
    });

    return strs.join("");
};

全部评论

相关推荐

04-02 16:49
门头沟学院 Java
_bloodstream_:我也面了科大讯飞,主管面的时候听说急招人优先考虑能尽快实习的,我说忙毕设,后面就一直没消息了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务