-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path008.StringToInteger.js
More file actions
49 lines (41 loc) · 1.03 KB
/
Copy path008.StringToInteger.js
File metadata and controls
49 lines (41 loc) · 1.03 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
// 解法一
function myAtoi1(str) {
const MAXSIGNINT = 2147483647
let result = parseInt(str, 10)
if (Number.isNaN(result)) {
result = 0
} else if (result > MAXSIGNINT) {
result = MAXSIGNINT
} else if (result < -(MAXSIGNINT + 1)) {
result = -(MAXSIGNINT + 1)
}
return result
}
// 解法二
function myAtoi2(str) {
const MAXSIGNINT = 2147483647
const mappings = new Map()
let result = 0
for (let i = 48; i < 58; i++) {
mappings.set(String.fromCharCode(i), i - 48)
}
str = str.trim()
if (mappings.has(str[0]) || ['+', '-'].indexOf(str[0]) !== -1) {
const sign = str[0] === '-' ? -1 : 1
for (let i = (sign === -1 || str[0] === '+') ? 1 : 0; i < str.length; i++) {
if (mappings.has(str[i])) {
result *= 10
result += mappings.get(str[i])
} else {
break
}
}
result *= sign
if (sign === -1 && result < -(MAXSIGNINT + 1)) {
result = -(MAXSIGNINT + 1)
} else if (result > MAXSIGNINT) {
result = MAXSIGNINT
}
}
return result
}