示例:
输入:s = “4193 with words”
输出:4193
解释:
第 1 步:“4193 with words”(当前没有读入字符,因为没有前导空格)
^
第 2 步:“4193 with words”(当前没有读入字符,因为这里不存在 ‘-’ 或者 ‘+’)
^
第 3 步:“4193 with words”(读入 “4193”;由于下一个字符不是一个数字,所以读入停止)
^
解析得到整数 4193 。
由于 “4193” 在范围 [-231, 231 - 1] 内,最终结果为 4193 。
输入:s = “words and 987”
输出:0
解释:
第 1 步:“words and 987”(当前没有读入字符,因为没有前导空格)
^
第 2 步:“words and 987”(当前没有读入字符,因为这里不存在 ‘-’ 或者 ‘+’)
^
第 3 步:“words and 987”(由于当前字符 ‘w’ 不是一个数字,所以读入停止)
^
解析得到整数 0 ,因为没有读入任何数字。
由于 0 在范围 [-231, 231 - 1] 内,最终结果为 0 。
test(str) {
str = str.trim();
let num = "";
if ((str[0] >= 0 && str[0] <= 9) || str[0] == "-" || str[0] == "+") {
for (let i = 0; i < str.length; i++) {
if ((str[i] >= 0 && str[i] <= 9) || str[0] == "-" || str[0] == "+") {
num += str[i];
} else {
break;
}
}
} else {
num = 0;
}
num = num - 0;
if (num < Math.pow(-2, 31)) {
num = Math.pow(-2, 31);
} else if (num > Math.pow(2, 31) - 1) {
num = Math.pow(2, 31) - 1;
}
console.log(num);
},
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-integer-atoi
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。