去掉空格,正则匹配出数字和符号位。然后转成数字。并判断下是否超出范围。
var myAtoi = function (str) {
str = str.trim(); //去掉空格
if (str.length = 0) {
return ""
}
var reg = reg = /^[\+|\-]?[0-9]+/
var numStr = str.match(reg);
if (!numStr) return 0;
var num = parseInt(numStr[0])
if (num > Math.pow(2, 31) - 1) {
return Math.pow(2, 31) - 1
}
if (num < -Math.pow(2, 31)) {
return -Math.pow(2, 31)
}
return num;
};