- 去除字符串两边空格后,排除没有资格转成数字的情况,代码如下所示,请看代码注释解析
if (["+", "-"].includes(str[0])) {// 字符串首位有+ - 号
if (!reg.test(str[1])) {// 然后第二位字符 却不是一个数字 这时候返回0
return 0;
}
} else {// 当没有首页符号时,进一步判断 首位不是数字 则也断定不满足转数字要求
if (!reg.test(str[0])) {
return 0;
}
}
2.剩下的就是 满足转数字要求的字符串了,for循环遍历字符串,请看代码注释
const nums = [];
const len = str.length;
for (let i = 0; i < len; i++) {
if (nums.length == 0) {// 第一次nums为[] 满足条件
if (str[i] === "-") {// 这时候i为0 如果str[0] 是正负号则跳过一次循环,下次循环i
// 下次循环 i = 1,这时候肯定不满足条件,之后的循环都不会因为正负号而断开了,
isNegative = true;
continue;
} else if (str[i] === "+") {
continue;
}
}
if (reg.test(str[i])) {// 上面代码已经考虑到了 正负号的问题,接下来如果剩下的字符是数字,则放入数字数组中,但凡遇到一个字符不是数字,则会终止循环
nums.push(str[i]);
} else {
break;
}
}
3.正负性已经有inNegative记录了,nums有包含了所有有效的数字,接下来就是组装了,组装完成后,
根据题目意思 它的值不能超过[-(2 ** 31), 2 ** 31 - 1]范围,其中a**b 就是Math.pow(a,b)
,超过了就按最近的最值输出
const strToInt = (str) => {
str = str.trim();
const reg = /\d/;
let isNegative = false;
if (["+", "-"].includes(str[0])) {
if (!reg.test(str[1])) {
return 0;
}
} else {
if (!reg.test(str[0])) {
return 0;
}
}
const nums = [];
const len = str.length;
for (let i = 0; i < len; i++) {
if (nums.length == 0) {
if (str[i] === "-") {
isNegative = true;
continue;
} else if (str[i] === "+") {
continue;
}
}
if (reg.test(str[i])) {
nums.push(str[i]);
} else {
break;
}
}
let res = 0;
const v = nums.length;
for (let i = v - 1; i >= 0; i--) {
res += nums[i] * 10 ** (v - 1 - i);
}
const [MIN, MAX] = [-(2 ** 31), 2 ** 31 - 1];
return isNegative ? (-res < MIN ? MIN : -res) : res > MAX ? MAX : res;
};