<AI/>
enru
All posts

String to integer (atoi)

LeetCode 8: Implement atoi to convert a string into a 32-bit signed integer, handling whitespace, signs and overflow.

Difficulty
Medium
Published
Topics
#string
Open on LeetCode

Problem Description

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

The function must follow these rules when reading the string:

  1. Skip any leading whitespace.
  2. Check for a sign (+ or -).
  3. Read the following characters as long as they form a sequence of digits.
  4. Convert those digits into an integer.
  5. If the first non-whitespace sequence of characters is not a valid integer, return 0.
  6. If the resulting value is outside the 32-bit signed integer range, return INT_MAX (231 - 1) or INT_MIN (-231).

Constraints

  • The string length is in the range from 0 to 200
  • s consists of English letters (both upper and lower case), digits, ' ' (space), '+', '-' and '.'.

Examples

Input: "42"

Answer: 42

We convert the string "42" into the integer 42.

Solution

To convert the string into a number, we iterate over its characters, checking all the required conditions.

First, we need to skip all leading spaces. For this we run a while loop that increments the index variable, which marks the position where the number starts.

Then we check whether the string specifies a sign. For this we keep a variable sign.

  • If we see +, we set sign to 1.
  • If we see -, we set sign to -1.

If a sign was present, we also increment index by one.

Now we just need to convert the remaining characters into a number. To check whether a character is a digit without type conversion, we can use a small trick and compare it with strings.

  • If char < "0" or char > "9", the character is not a digit. As soon as we meet a non-digit character, we stop parsing.
  • If the character is a digit, we add it to the resulting number using the formula res = res * 10 + char - '0'. This appends the digit on the right of the existing number.

After that, we check whether the number has exceeded the minimum or maximum value.

  • If the maximum is exceeded, we return the maximum.
  • If the minimum is exceeded, we return the minimum.

Finally, we return res multiplied by sign.

typescript
export function myAtoi(s: string): number {
  const maxInt32 = 2 ** 31 - 1;
  const minInt32 = 2 ** 31 * -1;
 
  let res = 0;
  let sign = 1;
  let index = 0;
 
  while (index < s.length && s[index] === ' ') {
    index++;
  }
 
  if (index < s.length && s[index] === '-') {
    sign = -1;
    index++;
  } else if (index < s.length && s[index] === '+') {
    index++;
  }
 
  for (let i = index; i < s.length; i++) {
    const char = s[i];
 
    if (char < '0' || char > '9') {
      break;
    }
 
    res = res * 10 + (char.charCodeAt(0) - '0'.charCodeAt(0));
    if (sign * res > maxInt32) {
      return maxInt32;
    }
    if (sign * res < minInt32) {
      return minInt32;
    }
  }
 
  if (res === 0) {
    // Handle the case when res = 0 and sign = -1. Otherwise JS would return "-0"
    return res;
  }
 
  return sign * res;
}

Complexity Analysis

n is the length of the string.

Time Complexity

The time complexity is linear: O(n), since in the worst case we iterate over all characters of the string.

Space Complexity

The space complexity is constant: O(1), since we don't create any additional data structures.