1 var myAtoi = function(str) {
2 var res = 0, 3 i = 0, 4 isNegtive = false, 5 isFirst = true; 6 7 8 for (i = 0; i < str.length; i++) { 9 if (isFirst && str[i] === ' ') { 10 continue; 11 } else if (isFirst && (str[i] === '-' || str[i] === '+')) { 12 isNegtive = str[i] === '-' ? true : false; 13 isFirst = false; 14 } else if (str[i] >= '0' && str[i] <= '9') { 15 res = res * 10 + (str[i] - '0'); 16 isFirst = false; 17 } else { 18 break; 19 } 20 } 21 22 res = isNegtive ? -res : res; 23 24 if (res > 2147483647) { 25 res = 2147483647; 26 } else if (res < -2147483648) { 27 res = -2147483648; 28 } 29 30 return res; 31 }; 32 33 console.log(myAtoi(" -0012a42"));