-
Notifications
You must be signed in to change notification settings - Fork 4
/
709.To_Lower_Case.js
46 lines (45 loc) · 1.18 KB
/
709.To_Lower_Case.js
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
/**
* @param {string} str
* @return {string}
*/
var toLowerCase = function (str) {
/**
* 解法1:取码转码
* 利用ASCII码进行转换
* https://en.wikipedia.org/wiki/ASCII
* A 65 a 97
* 利用大小写相差32位的特性,x+32后转为字符即可
* 方法:"x".charCodeAt(), String.fromCharCode()
*/
const upperRange = { min: 65, max: 90 };
const lowerArr = [];
for (let i = 0; i < str.length; i++) {
const code = str[i].charCodeAt();
if (code >= upperRange.min && code <= upperRange.max) {
lowerArr.push(String.fromCharCode(code + 32));
} else {
lowerArr.push(str[i]);
}
}
const result = lowerArr.join("");
return result;
/**
* 解法2:"foo".toLowerCase();
*/
return str.toLowerCase();
};
// TypeScript版
function toLowerCase(str: string): string {
const upperRange = { min: 65, max: 90 };
const lowerArr = [];
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code >= upperRange.min && code <= upperRange.max) {
lowerArr.push(String.fromCharCode(code + 32));
} else {
lowerArr.push(str[i]);
}
}
const result = lowerArr.join("");
return result;
}