/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. If the next character is + or -, determine the sign of the integer. If neither is present, assume positive.

3. Read consecutive digits and convert them to an integer. Stop reading when a non-digit character is encountered or the end of the string is reached. If no digits are read, return 0.

4. Clamp the result to the 32-bit signed integer range: [-231, 231 - 1].

Return the resulting integer.

Example 1

Input: +0075abc

Output: 75

Explanation: Leading whitespace ignored, + sign detected, digits 0075 parsed, result is 75.

Example 2

Input: -123xyz

Output: -123

Explanation: Leading whitespace ignored, - sign detected, digits 123 parsed, result is -123.

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: -91283472332

Output: -2147483648

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

Constraints

  • 0 <= len(input_string) <= 200
  • input_string 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: ' +000123foo'

Expected: 123

Case 2

Input: ' -000987bar'

Expected: -987

Case 3

Input: ' 0000baz'

Expected: 0

Case 4

Input: '9999999999abc'

Expected: 2147483647

Case 5

Input: ' -9999999999xyz'

Expected: -2147483648

Case 6

Input: ' .123'

Expected: 0

Case 7

Input: ' +abc'

Expected: 0

Case 8

Input: ' -'

Expected: 0