FreeCodeCamp-JavaScript Algorithms and Caesars Cipher

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"));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值