Skip to content

Commit 3635fac

Browse files
committed
凯撒密码
1 parent 800b2c5 commit 3635fac

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

凯撒密码.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# 翻转字符串 (参考自: [FreeCodeCamp 初级算法题 - 凯撒密码](https://singsing.io/blog/fcc/basic-reverse-a-string/#more))
2+
### 描述:function接收一个需要解密的字符串,返回解密后的字符串。解题过程可以通过ROT13加密实现。ROT13加密的原理就是偏移13位,大小写保持不变。
3+
4+
### 解题思路:
5+
* 判断大小写可以通过.charCodeAt()返回的ASCII码来判断,或者使用正则。
6+
* 如果当前字符为A~M之间,对应的ASCII码范围是65-77,ROT13加密应该给ASCII码加13
7+
* 如果当前字符为N~Z之间,对应的ASCII码范围是78-90,ROT13加密应该给ASCII码减13
8+
9+
```
10+
function rot13(str){
11+
var result = '';
12+
for(let i=0;i<str.length;i++){
13+
let currentCode = str[i].charCodeAt()
14+
if(currentCode > 90 || currentCode < 65){
15+
// 非大写字符
16+
result += String.fromCharCode(currentCode);
17+
} else if (currentCode < 78){
18+
// A~M
19+
result += String.fromCharCode(currentCode + 13);
20+
} else {
21+
// N~Z
22+
result += String.fromCharCode(currentCode - 13);
23+
}
24+
}
25+
return result
26+
}
27+
```
28+
### 优化
29+
#### 思路:n%2输出0和1,n%3输出0,,1,2,n%m输出0至m-1,因此我们可以确定65-90的范围(n%26) + 65
30+
```
31+
function rot13(str) {
32+
let result = "";
33+
for (let i = 0; i < str.length; i++) {
34+
if (/[A-Z]/.test(str[i])) {
35+
result += String.fromCharCode(str[i].charCodeAt() % 26 + 65);
36+
} else {
37+
result += str[i];
38+
}
39+
}
40+
return result;
41+
}
42+
```
43+
通过链式调用,减少变量声明。
44+
45+
### 进一步简化代码,使用String.replace()
46+
* [String.replace()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
47+
* [String.fromCharCode()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode)
48+
```
49+
function rot13(str) {
50+
return str.replace(/[A-Z]/g, char => String.fromCharCode(char.charCodeAt() % 26 + 65));
51+
}
52+
```

0 commit comments

Comments
 (0)