字符串加解密
作者:互联网
题目:
解析:
-
本题的解决思路 操作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
}
欢迎交流
标签:String,temp,加解密,else,result,str,字符串,fromCharCode 来源: https://blog.csdn.net/qq_36579455/article/details/114830407