String to Integer (atoi)
Medium Parsing with overflow clamp
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Parse an integer from a string: skip leading spaces, read an optional sign, read digits until a non-digit, and clamp the result to the 32-bit range.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: read an integer the way C's atoi does: spaces, sign, digits, then stop; clamp to int range.
Why this works: do the steps in order, and check for overflow before adding each digit.
Example: " -42abc"
skip spaces → '-' signdigits 4, 2 → 42, stop at 'a'→ -42
✦Hints open one at a time
↗Approach
Walk with an index. After spaces and sign, for each digit check result > (MAX - d) / 10; if so, return the clamped limit for the sign. Otherwise result = result * 10 + d.
</>Solution (Java)
class Solution {
public int myAtoi(String s) {
int i = 0, n = s.length(), sign = 1, result = 0;
while (i < n && s.charAt(i) == ' ') i++;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = s.charAt(i) == '-' ? -1 : 1;
i++;
}
while (i < n && Character.isDigit(s.charAt(i))) {
int d = s.charAt(i) - '0';
if (result > (Integer.MAX_VALUE - d) / 10) { // next step would overflow
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + d;
i++;
}
return sign * result;
}
}
!Common mistake
Using Integer.parseInt or a long without limit checks — very long digit strings still overflow a long.
- Time: O(n).
- Space: O(1).