Caesars Cipher
One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.
A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus A ↔ N, B ↔ O and so on.
Write a function which takes a ROT13 encoded string as input and returns a decoded string.
All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
Instance Image
Instance Code
let letters = ["A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
let index = 0;
function rot13(str) {
let arr = str.split("");
if(index < str.length){
const name = arr[index];// 当前字母
if(" " !== name && "!" !== name && "?" !== name && "." !== name){// 字母解析存入
let ind = letters.indexOf(name) + 13;// 下标前移动13位
let jindex = ind > letters.length
? (ind == letters.length ? 0 : letters.length - ind - 1 )
: (ind == letters.length ? 0 : ind );
jindex = jindex.toString();
if(jindex.match("-")){
jindex = jindex.replace("-","");
jindex -= 1;
}
arr[index] = letters[jindex];
}else {// 空格特殊字符直接存入
arr[index] = name;
}
// 遍历
index++;
let arrs = rot13(arr.join(""));
return arrs;
}else {
index = 0;
}
return arr.join("");
}
console.log("result:"+rot13("SERR PBQR PNZC"));