Problem
Implement the conversion of a string to a 32-bit signed integer, following the usual atoi rules: leading whitespace, an optional sign, a run of digits, then clamp the result into the range from -2³¹ to 2³¹-1.
Original: LeetCode 8: String to Integer (atoi).
Examples
Example 1
`s = "42"``42`Example 2
`s = " -42"``-42`Example 3
`s = "1337c0d3"``1337`Example 4
`s = "0-1"``0`Example 5
`s = "words and 987"``0`Example 6
`s = "2147483648"``2147483647`Example 7
`s = "-2147483649"``-2147483648`Constraints
0 <= s.length <= 200sconsists of English letters (lower-case and upper-case), digits (0 - 9),' ','+','-', and'.'.
Hints
Hint 1
The function must be robust: extra characters after the number are ignored, and overflow does not wrap, it clamps. If no digits are read, the result is 0.
Hint 2
This is careful input parsing: a small state machine for whitespace, sign and digits, with an overflow check on every new digit.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Regular expressions can pick out the number, but overflow and the exact character rules are still your responsibility.
Optimal. A single left-to-right scan with a long or a pre-check against Integer.MAX_VALUE / 10 before multiplying by ten.
Alternative. Integer.parseInt after trimming is not enough, because it throws on extra characters and on overflow instead of clamping.
Complexity
- Time
- O(n)
O(n) time, O(1) extra space.
- Space
- O(1)
Code
def my_atoi(s: str) -> int:
i, n = 0, len(s)
while i < n and s[i] == " ":
i += 1
sign = 1
if i < n and s[i] in "+-":
sign = -1 if s[i] == "-" else 1
i += 1
val = 0
int_max, int_min = 2**31 - 1, -(2**31)
while i < n and s[i].isdigit():
val = val * 10 + int(s[i])
if sign == 1 and val > int_max:
return int_max
if sign == -1 and -val < int_min:
return int_min
i += 1
return sign * val
if __name__ == "__main__":
assert my_atoi("42") == 42
assert my_atoi(" -42") == -42
assert my_atoi("1337c0d3") == 1337
assert my_atoi("0-1") == 0
assert my_atoi("words and 987") == 0
assert my_atoi("2147483648") == 2**31 - 1
assert my_atoi("-2147483649") == -(2**31)
print("ok")public class StringToIntegerAtoi {
static int myAtoi(String s) {
int i = 0, n = s.length();
while (i < n && s.charAt(i) == ' ') i++;
int sign = 1;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = s.charAt(i) == '-' ? -1 : 1;
i++;
}
long val = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
val = val * 10 + (s.charAt(i) - '0');
if (sign == 1 && val > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign == -1 && -val < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int) (sign * val);
}
public static void main(String[] args) {
if (myAtoi("42") != 42) throw new AssertionError();
if (myAtoi(" -42") != -42) throw new AssertionError();
if (myAtoi("1337c0d3") != 1337) throw new AssertionError();
if (myAtoi("0-1") != 0) throw new AssertionError();
if (myAtoi("words and 987") != 0) throw new AssertionError();
if (myAtoi("2147483648") != Integer.MAX_VALUE) throw new AssertionError();
if (myAtoi("-2147483649") != Integer.MIN_VALUE) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples include "42" becoming 42, " -42" becoming -42, "1337c0d3" becoming 1337, "0-1" becoming 0, and "words and 987" becoming 0.
- Values above 2³¹-1 clamp to 2³¹-1, and values below -2³¹ clamp to -2³¹.
- A sign with no following digits yields 0.
Follow-ups
- The same scan can be extended to floats, hex, or an explicit error instead of clamping, depending on the product rule.
Interview script
"I skip spaces, read an optional sign, then consume digits. Before I add a digit I check whether the value would leave the 32-bit range, and if it would, I clamp and return. Characters after the first non-digit are ignored, so '1337c0d3' is 1337."
Source: LeetCode 8: String to Integer (atoi) Source: Java SE 17 API: Integer.MAX_VALUE
Sources
Sources (2)
- LeetCode 8: String to Integer (atoi)leetcode.com
- Java SE 17 API: Integer.MAX_VALUEdocs.oracle.com