写一个函数StrToInt,实现把字符串转换成整数的功能。
可能的情况:
1.空字符串
2.正负号
3.前导零
4.空格
5.非数字字符
6.溢出
示例1
输入:123 abc
返回值:123
示例2
输入:012a3
返回值:12
function StrToInt(str) {
const INT_MIN = -Math.pow(2, 31);
const INT_MAX = Math.pow(2, 31) - 1;
let index = 0;
const n = str.length;
// 1. 跳过前导空格
while (index < n && str[index] === ' ') {
index++;
}
// 2. 判断是否为空或者全是空格
if (index === n) {
return 0;
}
// 3. 判断符号
let sign = 1;
if (str[index] === '+' || str[index] === '-') {
sign = (str[index] === '-') ? -1 : 1;
index++;
}
// 4. 读取数字部分
let result = 0;
while (index < n && /\d/.test(str[index])) {
const digit = parseInt(str[index], 10);
// 5. 检查溢出
if (
result > Math.floor((INT_MAX - digit) / 10)
) {
return sign === 1 ? INT_MAX : INT_MIN;
}
result = result * 10 + digit;
index++;
}
// 6. 应用符号
result *= sign;
return result;
}
1.空字符串
2.正负号
3.前导零
4.空格
5.非数字字符
6.溢出
示例1
输入:123 abc
返回值:123
示例2
输入:012a3
返回值:12
function StrToInt(str) {
const INT_MIN = -Math.pow(2, 31);
const INT_MAX = Math.pow(2, 31) - 1;
let index = 0;
const n = str.length;
// 1. 跳过前导空格
while (index < n && str[index] === ' ') {
index++;
}
// 2. 判断是否为空或者全是空格
if (index === n) {
return 0;
}
// 3. 判断符号
let sign = 1;
if (str[index] === '+' || str[index] === '-') {
sign = (str[index] === '-') ? -1 : 1;
index++;
}
// 4. 读取数字部分
let result = 0;
while (index < n && /\d/.test(str[index])) {
const digit = parseInt(str[index], 10);
// 5. 检查溢出
if (
result > Math.floor((INT_MAX - digit) / 10)
) {
return sign === 1 ? INT_MAX : INT_MIN;
}
result = result * 10 + digit;
index++;
}
// 6. 应用符号
result *= sign;
return result;
}
全部评论
相关推荐