字符串加解密

题目:

在这里插入图片描述

解析:

  • 本题的解决思路 操作ASCII码 。
    0~9 ASCII对应为 48 - 57
    A~Z ASCII对应为 65 - 90
    a~z ASCII对应为 97 - 122

  • ASCII码与字符之间的转化, String.fromCharCode(code) code = str[i].charCodeAt()

代码产出:

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var count = 0
rl.on('line', function (line) {
    if(count === 0) {
        console.log(Encrypt(line))
        count ++
    } else {
        console.log(Decrypt(line))
        count = 0
    }
});

// 加密
var Encrypt = (str) => {
    let result = ''
    for(let i=0;i<str.length;i++) {
        const temp = str[i].charCodeAt()
        if (temp >= 48 && temp <= 57) {
            if(temp === 57) { // 当是个数字9
                result += '0'
            } else {
                result += String.fromCharCode(temp+1)
            }
        } else if(temp >= 65 && temp <= 90) {
            if(temp === 90) { // 当是个大写字母 Z
                result += 'a'
            } else {
                result += String.fromCharCode(temp+1).toLowerCase()
            }
        } else if(temp >= 97 && temp <= 122) {
            if(temp === 122) { // 当是个小写字母 z
                result += 'A'
            } else {
                result += String.fromCharCode(temp+1).toUpperCase()
            }
        } else {
            result += str[i]
        }
    }
    return result
}

// 解密
var Decrypt = (str) => {
    let result = ''
    for(let i=0;i<str.length;i++) {
        const temp = str[i].charCodeAt()
        if (temp >= 48 && temp <= 57) {
            if(temp === 48) { // 当是个数字9
                result += '9'
            } else {
                result += String.fromCharCode(temp-1)
            }
        } else if(temp >= 65 && temp <= 90) {
            if(temp === 65) { // 当是个大写字母 A
                result += 'z'
            } else {
                result += String.fromCharCode(temp-1).toLowerCase()
            }
        } else if(temp >= 97 && temp <= 122) {
            if(temp === 97) { // 当是个小写字母 a
                result += 'Z'
            } else {
                result += String.fromCharCode(temp-1).toUpperCase()
            }
        } else {
            result += str[i]
        }
    }
    return result
}


欢迎交流

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值