8. 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:

  • Whitespace: Ignore any leading whitespace (" ").

  • Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.

  • 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.

  • Rounding: If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1.

Return the integer as the final result.

題目連結

此題要針對輸入的字串進行判斷並取出最前面的完整字串來回傳,主要有上面提到的四個規則需要遵守,大致上是:

  • 忽略前後的空白

  • 第一個 +- 代表數字的正負

  • 讀到的字元是 0 的話可以繼續往下讀,直到遇到不是數字的字元為止,如果最後沒有合格的數字被讀進來或是只有讀到正負號的話就回傳 0

  • 當數字超過範圍 [231,2311][-2^{31}, 2^{31}-1] 的時候要把數字強制縮進去 (直接轉成兩邊的極值值)

思路

此題主要是針對輸入字串進行依序的判讀,首先會需要把頭尾的空白先去除,使用到 strip() 方法,接下來就根據遇到的字元類型來進行判斷,需要注意的是針對正負號的部分只取 index 為 0,也就是最前面的才納入考量 (因為已經去除頭尾的空白),如果正負號不在第一個的話也視作停止條件。

使用一個空字串來依序把讀到的數字加進去,讀完之後再將其轉換為整數,並且檢查是否在限制的範圍之內後即可輸出結果。

Full Code

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.strip()
        resStr = ""

        for i, char in enumerate(s):
            if i == 0 and char in ["+", "-"]:
                resStr += char
                continue
            if not char.isdigit():
                break
            resStr += char

        res = max(min(int(resStr) if resStr not in ["", "+", "-"] else 0, 2**31 - 1), -2**31)
        return res

Copyright© 2026 ZeoXer. All Rights Reserved.