著名的凯撒密码Caesar cipher,又叫移位密码。
移位密码也就是密码中的字母会按照指定的数量来做移位。
一个常见的案例就是ROT13密码,字母会移位13个位置。由’A’ ↔ ‘N’, ‘B’ ↔’O’,以此类推。
写一个ROT13函数,实现输入加密字符串,输出解密字符串。
所有的字母都是大写,不要转化任何非字母形式的字符(例如:空格,标点符号),遇到这些特殊字符,就跳过它们。
下面贴出个人写的代码,搜过其他答案,复杂难懂。对比之下,小小的自豪。
function rot13(str) {
var strs = str.split("");
for (var i = 0; i < strs.length; i++) {
var index = str.charCodeAt(i);
if (64 < index && index <= 90 ) {
if(index + 13 > 90){
index = index - 13;
} else {
index = index + 13;
}
strs[i] = String.fromCharCode(index);
} else {
continue;
}
}
return strs.join("");
}
美滋滋~