
位移密码算法挑战
方法一:
function rot13(str) { // LBH QVQ VG!
function rot13char(char){
if (char.charCodeAt()>=65&&char.charCodeAt()<=90){
return char.charCodeAt()>=78?String.fromCharCode(char.charCodeAt()-13):String.fromCharCode(char.charCodeAt()+13);
}else
return char;
}
str=str.split("").map(rot13char).join("");
return str;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
方法二:
function rot13(str) { // LBH QVQ VG!
var len = str.length,
rStr = '';
for(var i=0;i<len;i++){
var n = str.charCodeAt(i),
c = str.charAt(i);
if(n >64 && n<91){
if(n+13<91){
c = String.fromCharCode(n+13);
}else{
c = String.fromCharCode(64+n+13-90);
}
}
rStr+=c;
}
return rStr;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");