-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path008-StringToInteger(atoi).js
More file actions
55 lines (46 loc) · 1.39 KB
/
008-StringToInteger(atoi).js
File metadata and controls
55 lines (46 loc) · 1.39 KB
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
//-----------------------------------------------------------------------------
// Runtime: 122ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
var navigate = false;
var index = 0;
while (index < str.length && str[index] === ' ') {
index++;
}
if (index === str.length) { return 0; }
if (str[index] === '-') {
navigate = true;
index++;
} else if (str[index] === '+') {
index++;
}
// 2147483647
var positiveOverflowHead = 214748364;
var positiveOverflowTail = 7;
var result = 0;
while (index < str.length) {
if (str[index] < '0' || str[index] > '9') { break; }
var digit = str[index] - '0';
if (result > positiveOverflowHead ||
(result === positiveOverflowHead && digit > positiveOverflowTail)) {
return navigate ? -2147483648 : 2147483647;
}
result = result * 10 + digit;
index++;
}
if (!result) { return 0; }
return navigate ? -result : result;
};
return {
myAtoi: myAtoi
};
};
module.exports = solution();