LeetCode 8. 字符串轉換整數 (atoi) String to Integer (atoi)

Table of Contents

一、中文版

二、英文版

三、My answer

四、解題報告


一、中文版

請你來實現一個 atoi 函數,使其能將字符串轉換成整數。

首先,該函數會根據需要丟棄無用的開頭空格字符,直到尋找到第一個非空格的字符爲止。接下來的轉化規則如下:

如果第一個非空字符爲正或者負號時,則將該符號與之後面儘可能多的連續數字字符組合起來,形成一個有符號整數。
假如第一個非空字符是數字,則直接將其與之後連續的數字字符組合起來,形成一個整數。
該字符串在有效的整數部分之後也可能會存在多餘的字符,那麼這些字符可以被忽略,它們對函數不應該造成影響。
注意:假如該字符串中的第一個非空格字符不是一個有效整數字符、字符串爲空或字符串僅包含空白字符時,則你的函數不需要進行轉換,即無法進行有效轉換。

在任何情況下,若函數不能進行有效的轉換時,請返回 0 。

提示:

本題中的空白字符只包括空格字符 ' ' 。
假設我們的環境只能存儲 32 位大小的有符號整數,那麼其數值範圍爲[−231,  231 − 1]。如果數值超過這個範圍,請返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。

示例 1:

輸入: "42"
輸出: 42
示例 2:

輸入: "   -42"
輸出: -42
解釋: 第一個非空白字符爲 '-', 它是一個負號。
     我們儘可能將負號與後面所有連續出現的數字組合起來,最後得到 -42 。
示例 3:

輸入: "4193 with words"
輸出: 4193
解釋: 轉換截止於數字 '3' ,因爲它的下一個字符不爲數字。
示例 4:

輸入: "words and 987"
輸出: 0
解釋: 第一個非空字符是 'w', 但它不是數字或正、負號。
     因此無法執行有效的轉換。
示例 5:

輸入: "-91283472332"
輸出: -2147483648
解釋: 數字 "-91283472332" 超過 32 位有符號整數範圍。 
     因此返回 INT_MIN (−231) 。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/string-to-integer-atoi
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

二、英文版

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:

Input: "42"
Output: 42
Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

 

三、My answer

class Solution:
    def myAtoi(self, str: str) -> int:
        max_int = 2 ** 31 - 1
        min_int = -2 ** 31
        if not str:
            return 0
        str = str.strip()
        flag = 1
        idx = 0
        if str and (str[0] in ('+-')):
            flag = -1 if str[0] == '-' else 1
            idx = 1
        res = 0
        for i in range(idx, len(str)):
            if str[i] in ('0123456789'):
                if res > max_int // 10 or (res == max_int // 10 and (ord(str[i]) - ord('0') > 7)):
                    if flag == 1:
                        return max_int
                    else:
                        return min_int
                res = res * 10 + ord(str[i]) - ord('0')
            else:
                break
        return res * flag
        

四、解題報告

難點:case 太多,容易想不到。

需要考慮的點:

1、是否越界(最大最小值)

2、數字正負

3、去掉左邊的空格後字符串是否爲空

4、在 res * 10 之前要判斷,乘以 10 之後會不會越界。
5、使用 ASCII 碼來計算數值,Python 中寫法是:ord(str[i]) - ord('0'),不能寫成 int(str[i])。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章