-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcaesar.js
More file actions
48 lines (44 loc) · 1.21 KB
/
caesar.js
File metadata and controls
48 lines (44 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
*
* 凯撒密码 - 简单的替换加密
*
* 问题:将字母表中的每个字母移动固定位数
*
* 核心思想:
* - 字母替换
* - 循环移位
* - 保持大小写
*
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
function caesarEncrypt(text, shift) {
let result = "";
for (let i = 0; i < text.length; i++) {
let c = text[i];
if (c >= 'A' && c <= 'Z') {
result += String.fromCharCode((c.charCodeAt(0) - 65 + shift) % 26 + 65);
} else if (c >= 'a' && c <= 'z') {
result += String.fromCharCode((c.charCodeAt(0) - 97 + shift) % 26 + 97);
} else {
result += c;
}
}
return result;
}
function caesarDecrypt(text, shift) {
return caesarEncrypt(text, 26 - (shift % 26));
}
function main() {
console.log("=== 凯撒密码 ===");
const text = "Hello, World!";
const shift = 3;
console.log("明文: " + text);
console.log("移位数: " + shift);
const encrypted = caesarEncrypt(text, shift);
console.log("加密后: " + encrypted);
const decrypted = caesarDecrypt(encrypted, shift);
console.log("解密后: " + decrypted);
console.log("验证: " + (text === decrypted));
}
main();