-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringtointeger.js
More file actions
37 lines (29 loc) · 935 Bytes
/
stringtointeger.js
File metadata and controls
37 lines (29 loc) · 935 Bytes
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
// Example 1:
// Input: s = "42"
// Output: 42
// Example 2:
// Input: s = " -42"
// Output: -42
// Example 3:
// Input: s = "4193 with words"
// Output: 4193
// Example 4:
// Input: s = "words and 987"
// Output: 0
// Example 5:
// Input: s = "-91283472332"
// Output: -2147483648
// If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
var myAtoi = function(s) {
var val = parseInt(s);
var result = val ? val : 0;
var lowerLimit = 2**31 * -1;
var upperLimit = 2**31 - 1;
if(result < 0) {
result = result <= lowerLimit ? lowerLimit : result;
} else {
result = result >= upperLimit ? upperLimit : result;
}
// console.log("result ", result)
return result
};