凱撤密碼
題目描述
讓上帝的歸上帝你雌,凱撒的歸凱撒器联。
下面我們來(lái)介紹風(fēng)靡全球的凱撒密碼Caesar cipher,又叫移位密碼婿崭。
移位密碼也就是密碼中的字母會(huì)按照指定的數(shù)量來(lái)做移位拨拓。
一個(gè)常見(jiàn)的案例就是ROT13密碼,字母會(huì)移位13個(gè)位置氓栈。由'A' ? 'N', 'B' ? 'O'渣磷,以此類推。
寫(xiě)一個(gè)ROT13函數(shù)授瘦,實(shí)現(xiàn)輸入加密字符串醋界,輸出解密字符串。
所有的字母都是大寫(xiě)奥务,不要轉(zhuǎn)化任何非字母形式的字符(例如:空格物独,標(biāo)點(diǎn)符號(hào))袜硫,遇到這些特殊字符氯葬,跳過(guò)它們刻诊。
代碼如下:
function rot13(str) { // LBH QVQ VG!
var index = null;
var temp = "";
var _A = "A".charCodeAt(0);
var _Z = "Z".charCodeAt(0);
var min = (_A+_Z)/2;
for(var i=0;i<str.length;i++){
index = str.charCodeAt(i);
if(index >= _A && index<=min){
temp += String.fromCharCode(index + 13);
} else if(index <= _Z && index >= min){
temp += String.fromCharCode(index - 13);
} else{
temp += String.fromCharCode(index);
}
}
return temp;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
涉及的知識(shí)點(diǎn)
- String.charCodeAt():返回指定位置的字符的Unicode編碼衰倦。
- String.fromCharCode():返回Unicode編碼對(duì)應(yīng)的字符串被丧。