-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
51 lines (44 loc) · 993 Bytes
/
res.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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-04-03 22:44:48
*
* Problem: Implement atoi to convert a string to an integer.
*
* @param {string} str
* @return {number}
*/
let myAtoi = function(str) {
const INT_MAX = 2147483647,
INT_MIN = -2147483648,
bound = Number.parseInt(INT_MAX / 10);
let strlen = str.length,
signal = 1, // 1 stands for positive number, 0 stands for negative number
res = 0;
while (str[0] && str[0] === ' ') {
str = str.slice(1);
strlen -= 1;
}
if (strlen === 0) {
return 0;
}
if (str[0] === '-') {
signal = 0;
str = str.slice(1);
} else if (str[0] === "+") {
str = str.slice(1);
}
while (str[0] >= '0' && str[0] <= '9') {
// console.log(str[0]);
let element = Number.parseInt(str[0]);
if (res > bound || (res === bound && element > 7)) {
if (signal) {
return INT_MAX;
}
return INT_MIN;
}
res = res * 10 + element;
str = str.slice(1);
}
return signal ? res : -res;
};