8. String to Integer (atoi) [easy] (Python)


タイトルリンク
https://leetcode.com/problems/string-to-integer-atoi/
タイトル
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
タイトル翻訳
「atoi」関数を実装し、文字列を整数に変換します.ヒント:可能なすべての入力状況をよく考えてください.
考え方
試行錯誤によって注意すべき4つの点をまとめることができます.
  • 入力文字列が空、またはその他の不正な場合は、0を返します.
  • 文字列の先頭のスペースは前処理で削除します.
  • 処理で発生する可能性のある正負号「+」,「-」,正負号は一度しか現れない.
  • 整数範囲を超えた値は、整数範囲の境界値をとる.

  • 考え方1
    上記の注意点に従って、比較的読みやすい解法は以下の通りです.
    コード#コード#
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            if not str:
                return 0
            str = str.strip()
            number, flag = 0, 1
            if str[0] == '-':
                str = str[1:]
                flag = -1
            elif str[0] == '+':
                str = str[1:]
            for c in str:
                if c >= '0' and c <= '9':
                    number = 10*number + ord(c) - ord('0')
                else:
                    break
            number = flag * number
            number = number if number <= 2147483647 else 2147483647
            number = number if number >= -2147483648 else -2147483648
            return number

    考え方2
    上記の手順を正規表現で簡略化します.
    コード#コード#
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            str = str.strip()
            try:
                res = re.search('(^[\+\-]?\d+)', str).group()
                res = int(res)
                res = res if res <= 2147483647 else 2147483647
                res = res if res >= -2147483648 else -2147483648
            except:
                res = 0
            return res

    PS:初心者はLeetCodeをブラシして、初心者はブログを書いて、書き間違えたり書いたりして、まだ指摘してください.ありがとうございます.転載は以下のことを明記してください.http://blog.csdn.net/coder_orz/article/details/52053932