Convert a string representation of an integer to a 32-bit signed integer.
Problem Statement
Examples
Input: s = "42"
Output: 42
Explanation: Combining the input according to String to Integer (atoi) logic yields 42.
Input: s = " -42"
Output: -42
Explanation: Combining the input according to String to Integer (atoi) logic yields -42.
Input: s = "1337c0d3"
Output: 1337
Explanation: Combining the input according to String to Integer (atoi) logic yields 1337.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Simulate the standard C atoi specification: ignore whitespace, parse optional sign, accumulate numeric digits, clamp to [-2^31, 2^31 - 1] upon overflow, and terminate upon encountering any non-digit character.
Step-by-Step Approach
- Skip leading whitespace with
i++. - Read optional
+or-sign. - Read contiguous digit characters
0-9. - Check for overflow against 32-bit boundaries.
- Return clamped signed result.
Optimal Implementation (JavaScript)
function myAtoi(s) {
let i = 0, n = s.length, sign = 1, res = 0;
while (i < n && s[i] === ' ') i++;
if (i < n && (s[i] === '+' || s[i] === '-')) sign = s[i++] === '-' ? -1 : 1;
const MAX = 2147483647, MIN = -2147483648;
while (i < n && s[i] >= '0' && s[i] <= '9') {
const d = s.charCodeAt(i++) - 48;
if (res > Math.floor(MAX / 10) || (res === Math.floor(MAX / 10) && d > 7)) {
return sign === 1 ? MAX : MIN;
}
res = res * 10 + d;
}
return sign * res;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty string or all spaces: returns 0.
- Sign followed by letters: returns 0.
- Extreme positive/negative overflow.