-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-to-integer.ts
59 lines (49 loc) · 1.12 KB
/
string-to-integer.ts
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
49
50
51
52
53
54
55
56
57
58
59
const signMap: Record<string, boolean> = {
"+": true,
"-": false,
};
const digitMap: Record<string, number> = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
};
export function myAtoi(s: string): number {
let isPositive = true;
let isLeading = true;
let result = 0;
for (let i = 0; i < s.length; ++i) {
let char = s[i];
if (char === " " && isLeading) {
continue;
}
if (char in signMap) {
if (isLeading) {
isLeading = false;
isPositive = signMap[char];
continue;
} else {
break;
}
}
if (char in digitMap) {
isLeading = false;
let digit = digitMap[char];
result = result * 10 + digit;
let limit = 2 ** 31 - (isPositive ? 1 : 0);
if (result >= limit) {
result = limit;
break;
}
continue;
}
break;
}
return (isPositive ? 1 : -1) * result;
}