AAlgoLoopSpaced repetition for LeetCode
MEDIUMStringLeetCode ↗

String to Integer (atoi)

The key idea

Process the string in four strict phases in order: skip leading spaces, read one optional sign, consume consecutive digits, and stop at the first non-digit. The only subtle part is clamping the running value to the 32-bit signed range [-2147483648, 2147483647] the moment it would overflow, so you never need a wider integer type.

Problem

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

1. Whitespace: ignore any leading whitespace (' ').
2. Signedness: determine the sign by checking if the next character is '-' or '+', assuming positivity if neither is present.
3. Conversion: read the next characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Rounding: if the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1.

Return the integer as the final result.

Constraints

Examples

Input: s = "42" Output: 42
Input: s = " -042" Output: -42
Input: s = "1337c0d3" Output: 1337

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More String problems