Skip to content

Commit 28dcddf

Browse files
committed
solved: 8
1 parent 5d961bf commit 28dcddf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

code/8.string-to-integer-atoi.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// @leet start
2+
function myAtoi(_s: string): number {
3+
const s = _s.trim();
4+
5+
if (!s) {
6+
return 0;
7+
}
8+
9+
let i = 0;
10+
11+
while (i < s.length) {
12+
const c = s[i];
13+
if (!("0" <= c && c <= "9") && c !== "." && c !== "-" && c !== "+") {
14+
break;
15+
}
16+
i++;
17+
}
18+
19+
const num = parseInt(s.slice(0, i), 10);
20+
21+
switch (true) {
22+
case isNaN(num):
23+
return 0;
24+
case num > Math.pow(2, 31) - 1:
25+
return Math.pow(2, 31) - 1;
26+
case num < -Math.pow(2, 31):
27+
return -Math.pow(2, 31);
28+
default:
29+
return num;
30+
}
31+
}
32+
// @leet end
33+

0 commit comments

Comments
 (0)