Convert a string to a 32-bit signed integer, following atoi parsing rules for whitespace, sign, digits, and overflow clamping.
atoi
gfgGiven a string s, interpret it as a 32-bit signed integer using rules similar to the classic atoi function.
Parse the string from left to right and build the integer result under these rules:
- Ignore any leading whitespace.
- Read at most one optional sign character:
+or-. - Read digits consecutively until the first non-digit character is reached.
- If no digits are read, the result is
0. - If the parsed value exceeds the 32-bit signed integer range, clamp it to the nearest bound.
Return the final integer value.
Input Format
- A single string
s.
The string may contain leading spaces, an optional sign, digits, and other trailing characters.
Output Format
- Return a single integer representing the parsed and clamped value.
Constraints
- The result must fit within the signed 32-bit integer range:
[$-2^{31}$, $2^{31}-1$]. - Parsing stops at the first character that is not a digit after optional leading spaces and sign.
- If no valid numeric prefix exists, return
0.
Example 1
Input
s = "42"
Output
42
Explanation
The string starts with digits, so the parsed integer is 42.
Example 2
Input
s = " -42"
Output
-42
Explanation
Leading spaces are ignored, then the negative sign is applied to the parsed digits.
Show 3 more examples
Example 3
Input
s = "4193 with words"
Output
4193
Explanation
Parsing stops when a non-digit character is encountered after reading digits.
Example 4
Input
s = "words and 987"
Output
0
Explanation
No valid numeric prefix starts at the beginning after skipping leading whitespace.
Example 5
Input
s = "-91283472332"
Output
-2147483648
Explanation
The value is smaller than the 32-bit signed minimum, so it is clamped.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.