/**
* 提取字符串中的整数。如果字符串开头空白字符,则忽略。从第一个不是空白字符的位置开始提取整数。注意整数前面可能有+、-号
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
var result = 0;
i = 0;
while(str[i] == ' ') {
i++;
}
var sign = 1,
len = str.length;
if(str[i] == '-' || str[i] == '+') {
if(str[i] == '-') sign = -1;
i++;
}
var upDivideTen = Math.floor(2147483647 / 10),
downDivideTen = Math.ceil(-2147483648 / 10);
while(str[i] !== ' ' && 0 <= str[i] && str[i] <= 9) { //0 <= ' '这个判断结果为true,所以应当加上字符不为空的限制
if(result > upDivideTen || (result == upDivideTen && str[i] > 7)) {
result = 2147483647;
break;
} else if (result < downDivideTen || (result == downDivideTen && str[i] > 8)){
result = -2147483648;
break;
}
result = result * 10 + sign * str[i];
i++;
}
return result;
};
leetcode_8. String to Integer (atoi)
最新推荐文章于 2021-08-09 11:38:54 发布