{x}
blog image

String to Integer (atoi)

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 present.
  3. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
  4. Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.

Return the integer as the final result.

 

Example 1:

Input: s = "42"

Output: 42

Explanation:

The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
         ^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "42" ("42" is read in)
           ^

Example 2:

Input: s = " -042"

Output: -42

Explanation:

Step 1: "   -042" (leading whitespace is read and ignored)
            ^
Step 2: "   -042" ('-' is read, so the result should be negative)
             ^
Step 3: "   -042" ("042" is read in, leading zeros ignored in the result)
               ^

Example 3:

Input: s = "1337c0d3"

Output: 1337

Explanation:

Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
         ^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
             ^

Example 4:

Input: s = "0-1"

Output: 0

Explanation:

Step 1: "0-1" (no characters read because there is no leading whitespace)
         ^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
          ^

Example 5:

Input: s = "words and 987"

Output: 0

Explanation:

Reading stops at the first non-digit character 'w'.

 

Constraints:

  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.

Solution Explanation: String to Integer (atoi)

This problem involves converting a string to a 32-bit signed integer. The solution presented follows a step-by-step approach outlined in the problem description:

1. Whitespace Handling: Leading whitespace characters are ignored.

2. Sign Determination: The sign (+ or -) is identified. If neither is present, the number is assumed positive.

3. Integer Conversion: Digits are read sequentially until a non-digit character is encountered or the string ends. Leading zeros are effectively ignored. If no digits are found, the result is 0.

4. Overflow Handling: The converted integer is checked against the 32-bit signed integer range [-231, 231 - 1]. Values outside this range are clamped to the respective boundaries.

Algorithm

The core algorithm efficiently handles each step:

  1. Whitespace Removal: The input string s is trimmed to remove leading and trailing spaces using str.trim() (or equivalent in other languages).

  2. Sign Check: The first non-whitespace character determines the sign. If it's '-' then sign is set to -1; otherwise, it's 1.

  3. Digit Conversion: A loop iterates through the remaining string. Each character is checked; if it's a digit, its integer value is calculated and accumulated into the res variable.

  4. Overflow Check: Before adding each digit, a check ensures that the result won't exceed the maximum or minimum 32-bit integer value. This is often done by comparing res with the maximum integer divided by 10, and then comparing the remainder with the current digit.

  5. Result: Finally, the result is multiplied by the sign to get the final signed integer.

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the input string. The algorithm iterates through the string at most once.

  • Space Complexity: O(1). The algorithm uses a constant amount of extra space to store variables like sign, res, and loop counters. It doesn't use any data structures that scale with input size.

Code Implementation (Python)

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.strip()  # Remove leading/trailing whitespace
        if not s:
            return 0
 
        sign = 1
        if s[0] == '-':
            sign = -1
            s = s[1:]
        elif s[0] == '+':
            s = s[1:]
 
        res = 0
        for char in s:
            if not char.isdigit():
                break
            res = res * 10 + int(char)
            if res > 2**31 - 1:
                return 2**31 - 1 if sign == 1 else -2**31
        return res * sign
 

The code in other languages (Java, Go, JavaScript, C#, PHP) implements the same algorithm, adapting syntax and data types as needed for each language. The core logic for whitespace handling, sign determination, digit conversion, and overflow prevention remains consistent across all implementations.