5. You want to implement
myAtoi that converts a string to a 32-bit signed integer. Which approach correctly handles overflow and returns the clamped value if the number is out of range?
function myAtoi(str) {
let i = 0, sign = 1, result = 0;
const INT_MAX = 2147483647;
const INT_MIN = -2147483648;
while (str[i] === ' ') i++;
if (str[i] === '-' || str[i] === '+') {
sign = str[i] === '-' ? -1 : 1;
i++;
}
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
let digit = str[i].charCodeAt(0) - '0'.charCodeAt(0);
if (result > Math.floor(INT_MAX / 10) || (result === Math.floor(INT_MAX / 10) && digit > INT_MAX % 10)) {
return sign === 1 ? INT_MAX : INT_MIN;
}
result = result * 10 + digit;
i++;
}
return sign * result;
}