-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8-string-to-integer-atoi.js
48 lines (47 loc) · 1.05 KB
/
8-string-to-integer-atoi.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
47
48
/**
* @param {string} s
* @return {number}
*/
var myAtoi = function (s) {
let number = "";
let leadingSpace = true;
let negative = false;
let startFindChar = false;
for (let i = 0; i < s.length; i++) {
let char = s.charAt(i);
if (char === " " && leadingSpace) {
continue;
} else {
leadingSpace = false;
}
if (!startFindChar && (char === "-" || char === "+")) {
negative = char === "-";
startFindChar = true;
continue;
}
if (s.charCodeAt(i) >= 48 && s.charCodeAt(i) <= 57) {
startFindChar = true;
number += char;
} else if (startFindChar) {
break;
} else {
return 0;
}
}
if (number === "") {
return 0;
}
let result = negative ? -parseInt(number) : parseInt(number);
let limit = Math.pow(2, 31);
if (result >= limit - 1) {
return limit - 1;
}
if (result < -limit) {
return -limit;
}
return result;
};
console.error(myAtoi("1337c0d3"));
console.error(myAtoi(" -042"));
console.error(myAtoi("words and 987"));
console.error(myAtoi(""));