字符串转换整数
累计相乘。
- 时间复杂度O(n),空间复杂度 O(1)
- Runtime: 84 ms, faster than 92.97%
- Memory Usage: 41.1 MB, less than 49.63%
/**
* @param {string} s
* @return {number}
*/
var myAtoi = function(s) {
s = s.replace(/(^\s*)|(\s*$)/g, '');
let len = s.length;
let max = Math.pow(2, 31) - 1;
let min = - Math.pow(2, 31);
let res = 0;
let flag = 1;
let start = 0;
if (s[0] === '+') {
start++;
} else if (s[0] === '-') {
start++;
flag = -1;
}
while (start < len) {
const val = s[start];
if (val > '9' || val < '0') {
break;
} else {
res = res * 10 + (val - '0');
}
start++;
}
res = res * flag;
if (flag < 0 && res < min) {
res = min;
} else if (flag > 0 && res > max) {
res = max;
}
return res;
};