/8. String to Integer (atoi)

8. String to Integer (atoi)

Medium
Strings20.7% acceptance

Implement a function that parses a string input and converts it to a 32-bit signed integer according to the following rules:

1. Ignore any leading whitespace characters.

2. Check for an optional + or - sign immediately following the whitespace. If neither is present, assume the number is positive.

3. Read consecutive digit characters and convert them to an integer. Stop reading when a non-digit character is encountered or the end of the string is reached.

4. If no digits are found, return 0.

5. Clamp the result to the 32-bit signed integer range: [-231, 231 - 1]. If the parsed integer is outside this range, return the closest boundary value.

Return the resulting integer.

Example 1

Input: +123abc

Output: 123

Explanation: Leading whitespace is ignored, + sign is detected, digits 123 are read, parsing stops at a, result is 123.

Example 2

Input: -00056xyz

Output: -56

Explanation: Leading whitespace is ignored, - sign is detected, leading zeros are ignored, digits 56 are read, parsing stops at x, result is -56.

Example 3

Input: abc123

Output: 0

Explanation: No digits at the start, so result is 0.

Example 4

Input: 2147483648

Output: 2147483647

Explanation: Parsed integer exceeds 32-bit signed max, so result is clamped to 2147483647.

Example 5

Input: -9999999999

Output: -2147483648

Explanation: Parsed integer exceeds 32-bit signed min, so result is clamped to -2147483648.

Constraints

  • 0 <= len(input_str) <= 200
  • input_str consists of English letters (a-z, A-Z), digits (0-9), whitespace ( ), plus (+), minus (-), and period (.)
  • Result must be clamped to [-231, 231 - 1]
Python (current runtime)

Case 1

Input: ' +789xyz'

Expected: 789

Case 2

Input: ' -0042.5'

Expected: -42

Case 3

Input: 'words123'

Expected: 0

Case 4

Input: ' 2147483647extra'

Expected: 2147483647

Case 5

Input: ' -2147483649abc'

Expected: -2147483648