- Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathstring_to_integer.js
More file actions
Latest commit
47 lines (46 loc) · 1.3 KB
/
Copy pathstring_to_integer.js
File metadata and controls
47 lines (46 loc) · 1.3 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
varmyAtoi=function(str){
// Base condition
if(!str){
return0;
}
// MAX and MIN values for integers
constINT_MAX=2147483647;
constINT_MIN=-2147483648;
// Trimmed string
str=str.trim();
// Counter
leti=0;
// Flag to indicate if the number is negative
constisNegative=str[0]==='-';
// Flag to indicate if the number is positive
constisPositive=str[0]==='+';
if(isNegative){
i++;
}elseif(isPositive){
i++;
}
// This will store the converted number
letnumber=0;
// Loop for each numeric character in the string iff numeric characters are leading
// characters in the string
while(i<str.length&&str[i]>='0'&&str[i]<='9'){
number=number*10+(str[i]-'0');
i++;
}
// Give back the sign to the converted number
number=isNegative ? -number : number;
if(number<INT_MIN){
returnINT_MIN;
}
if(number>INT_MAX){
returnINT_MAX;
}
returnnumber;
};
console.log(myAtoi("42"));
console.log(myAtoi(" -42"));
console.log(myAtoi("4193 with words"));
console.log(myAtoi("words and 987"));
console.log(myAtoi("-91283472332"));
console.log(myAtoi("91283472332"));
console.log(myAtoi("9223372036854775808"));