5. You want to extend the atoi function to handle integer overflow by clamping the result between
INT_MIN = -2147483648 and
INT_MAX = 2147483647. Which code snippet correctly clamps the value before returning?
const INT_MIN = -2147483648;
const INT_MAX = 2147483647;
function atoi(str: string): number {
let i = 0, num = 0, sign = 1;
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') {
num = num * 10 + (str.charCodeAt(i) - 48);
i++;
}
num = num * sign;
// Clamp here
// ???
return num;
}