string to integer 28atoi 29 javascript

Solutions on MaxInterview for string to integer 28atoi 29 javascript by the best coders in the world

showing results for - "string to integer 28atoi 29 javascript"
Theo
30 Mar 2016
1/**
2 * @param {string} str
3 * @return {number}
4 */
5var myAtoi = function(str) {
6  var i = 0;
7  var sign = 1;
8  var res = 0;
9  var len = str.length;
10  var INT_MAX = 2147483647;
11  var INT_MIN = - INT_MAX - 1;
12
13  while (str[i] === ' ') i++;
14
15  if (str[i] === '+' || str[i] === '-') {
16    sign = str[i] === '+' ? 1 : -1;
17    i++;
18  }
19
20  while (str[i] >= '0' && str[i] <= '9') {
21    res = (res * 10) + (str[i] - 0);
22    if (sign === 1 && res > INT_MAX) return INT_MAX;
23    if (sign === -1 && res > INT_MAX + 1) return INT_MIN;
24    i++;
25  }
26
27  return res * sign;
28};
29