Back to DSA

String to Integer (atoi)

medium
Acceptance: 41%
Strings

Write 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:123
Explanation: Leading spaces are ignored and the digits '123' are parsed as the integer 123.
Example 2:
Input:s = "-98abc"
Output:-98
Explanation: After the sign '-', digits '98' are consumed. Parsing stops at the non-digit character 'a'.

Hints

00:00
1234567