zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Caesars Cipher #304

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

挑战

凯撒密码,大写数字前移13位,为密码,求解码。

代码


function rot13(str) { // LBH QVQ VG!
  var convertStr=str.split("");
  var arr=[];

  var newStr="";
  for(var i=0;i<convertStr.length;i++){

    arr.push(convertStr[i].charCodeAt());

    if(arr[i]>=65 && arr[i]<=77){
      arr[i]+=13;    
    } else if(arr[i]>77 && arr[i]<=90){
      arr[i]+=(12-25);

    }  

  }

  var newString=String.fromCharCode.apply(null,arr);  

  return newString;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

结果显示

image

帮助

String.prototype.charCodeAt() String.fromCharCode()

来源

https://www.freecodecamp.org/challenges/caesars-cipher

zilongxuan001 commented 6 years ago

20180402参考Jason Luboff

代码


function rot13(str) { // LBH QVQ VG!
  var convertArray= str.split("");
  var newArray = [];
  for(i=0;i<convertArray.length;i++){
    newArray.push(convertArray[i].charCodeAt());
    if (newArray[i]>=65 && newArray[i]<=77){
      newArray[i] +=13;      
    } else if(newArray[i]>=78){
       newArray[i]=(newArray[i]+12)-25;
    }
  }

  var finalString=String.fromCharCode.apply(null,newArray);

  return finalString;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");
zilongxuan001 commented 6 years ago

Jason Luboff使用了fromCharCode.apply()方法。直接将数组变成字符串。

image

来源:https://jsperf.com/string-fromcharcode-apply-vs-string-fromcharcode-using-

zilongxuan001 commented 6 years ago

ASCII表 image

65代表A77代表M90代表Z

zilongxuan001 commented 6 years ago

一直纠结于标点符号如.,以及空格怎么转换,其实多此一举,因为if else限制了ASCII里大写字母的范围,标点符号和空格在范围之外,无需转换。