Caesars Cipher | shift cipher
字母偏移13位加密
'A' ↔ 'N', 'B' ↔ 'O' and so on
//"A".charCodeAt() 65
//"Z".charCodeAt() 90
//65 ~ 90, transform
function rot13(str) {
return str.replace(/[A-Z]/g, (match)=> {
let encodedASCII = match.charCodeAt()
if(encodedASCII < 78) {
//从5开始,往左数3次,5 -> 4 -> 3
//5 - 3 = 2,这个算法导致只数2次
//6 - 3 = 3,这样OK
//即从90往左数n次,要从91开始计算,91-n
return String.fromCharCode(91-(13-(encodedASCII-65)))
}
return String.fromCharCode(encodedASCII - 13)
})
}
rot13("SERR PBQR PNZC");
测试数据:
rot13("SERR PBQR PNZC") should decode to FREE CODE CAMP rot13("SERR CVMMN!") should decode to FREE PIZZA! rot13("SERR YBIR?") should decode to FREE LOVE? rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") should decode to THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
别人家的孩子
//利用 % 取余数,构建头尾相连队列
function rot13(str) {
return str.replace(/[A-Z]/g, L =>
String.fromCharCode((L.charCodeAt(0) % 26) + 65)
);
}
//头尾相连队列原理,remainder 美: [rɪ'meɪndər] 余数
0 % 5 = 0 because 0 / 5 = 0 and the remainder is 0.
1 % 5 = 1 because 1 / 5 = 0 and the remainder is 1
4 % 5 = 4 because 4 / 5 = 0 and the remainder is 4
5 % 5 = 0 because 5 / 5 = 1 and the remainder is 0
7 % 5 = 2 because 7 / 5 = 1 and the remainder is 2
9 % 5 = 4 because 9 / 5 = 1 and the remainder is 4
10 % 5 = 0 because 10 / 5 = 2 and the remainder is 0
//x % n,不论 x 有多大,值永远是 0 到 n 之间,因为 n 的余数不可能大于 n