题目描述:
凯撒密码Caesar cipher,又叫移位密码。
移位密码也就是密码中的字母会按照指定的数量来做移位。
一个常见的案例就是ROT13密码,字母会移位13个位置。由’A’ ↔ ‘N’, ‘B’ ↔ ‘O’,以此类推。
写一个ROT13函数,实现输入加密字符串,输出解密字符串。
所有的字母都是大写,不要转化任何非字母形式的字符(例如:空格,标点符号),遇到这些特殊字符,跳过它们。
题目分析:
由于所有的字母都是大写,在做变换的时候只需要把A-M的向后移13位,把N-Z的向前移13位,其余的保持不变。
str.charAt(index) : 从一个字符串中返回指定的字符, 比如 :
"Brave new world".charAt(0) // 'B'
str.charCodeAt(index) : 返回0到65535之间的整数, 是一个表示给定索引处(String中index索引处)字符的 UTF-16 代码单元值的数字,比如 :
"ABC".charCodeAt(0) // returns 65:"A"
String.fromCharCode(num1, …, numN) : 返回使用指定的Unicode值序列创建的字符串 , 比如
String.fromCharCode(65,66,67) // returns "ABC"
实现代码:
function rot13(str) { // LBH QVQ VG!
var newStr="";
for(var i=0;i<str.length;i++){
if(str.charAt(i)>='A'&&str.charAt(i)<='M'){
newStr +=(String.fromCharCode(str.charCodeAt(i)+13));
}else if(str.charAt(i)>='N'&&str.charAt(i)<='Z'){
newStr += (String.fromCharCode(str.charCodeAt(i)-26+13));
}else{
newStr += (str.charAt(i));
}
}
return newStr;
}
rot13("SERR PBQR PNZC");