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
1234567