-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstring_to_integer.js
53 lines (43 loc) · 1.23 KB
/
string_to_integer.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
49
50
51
52
53
/**
* @param {string} str
* @return {number}
*/
let isNegative;
var myAtoi = function(str) {
isNegative = 0;
str = str.trim();
if(str[0] === "-" || str[0] === "+" || !isNaN(str[0])) {
if(str[0] === "+") {
return checkNumber(str, 1);
} else if(!isNaN(str[0])) {
return checkNumber(str, 0);
} else {
if(str[0] === "-") {
isNegative = 1;
str = str.substring(1, str.length);
return checkNumber(str, 0);
}
}
} else {
return 0;
}
};
let checkNumber = (currentString, currentIndex) => {
let newNumber = "";
let INT_MIN = Math.pow(-2, 31);
let INT_MAX = Math.pow(2, 31) - 1;
for(let i = 0; i < currentString.length; currentIndex++, i++) {
if(isNaN(currentString.charAt(currentIndex)))
break;
if(currentString.charAt(currentIndex) === " ")
break;
newNumber += currentString.charAt(currentIndex);
}
if(isNegative)
newNumber *= -1;
if(newNumber < INT_MIN)
return INT_MIN;
else if(newNumber > INT_MAX)
return INT_MAX;
return newNumber;
}