Back to DSA
String to Integer (atoi)
mediumWrite a function that parses a string and extracts an integer from it, mimicking simplified integer-parsing behavior. The function should skip leading whitespace, recognize an optional '+' or '-' sign, then read consecutive digit characters. Convert the resulting digit sequence to an integer. If the value exceeds the 32-bit signed integer range [-2^31, 2^31 - 1], clamp it to the nearest boundary.
Examples
Example 1:
Input:
s = " 123"Output:
123Explanation: Leading spaces are ignored and the digits '123' are parsed as the integer 123.
Example 2:
Input:
s = "-98abc"Output:
-98Explanation: After the sign '-', digits '98' are consumed. Parsing stops at the non-digit character 'a'.
Hints
class Solution {
public int myAtoi(String s) {
int i = 0, n = s.length(), sign = 1;
long 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))) {
result = result * 10 + (s.charAt(i) - '0');
if (result * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int)(result * sign);
}
}Time complexity
O(n)Space complexity
O(1)