SDE & MLE Prep

8. String to Integer (atoi)

Problem

Implement myAtoi(s): skip leading spaces, read an optional + or -, then read digits until the first non-digit (leading zeros are fine). No digits gives 0. Clamp the result to the 32-bit signed range [−2³¹, 2³¹ − 1].

Example: "42" → 42; " -042" → -42; "1337c0d3" → 1337; "words 987" → 0

Skip spaces, read an optional sign, read digits until a non-digit; clamp to [−2³¹, 2³¹−1] (check before multiplying in Java).

Complexity: O(n).

class Solution:
    def myAtoi(self, s: str) -> int:
        i, n = 0, len(s)
        while i < n and s[i] == " ":
            i += 1
        sign = 1
        if i < n and s[i] in "+-":
            sign = -1 if s[i] == "-" else 1
            i += 1
        num = 0
        while i < n and s[i].isdigit():
            num = num * 10 + int(s[i])
            i += 1
        return max(-2 ** 31, min(2 ** 31 - 1, sign * num))