leetcode_algorithm8 String to Integer (atoi)

題目:

Implement atoi which converts a string to an integer.

(寫一個把字符串轉換爲數字的atoi函數接口)

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.

(如果str中的第一個非空字符不是一個數字或者由於字符串爲空或者只包含一個空字符,不執行轉換。如果不是一個有限轉換,則返回數值‘0’)

思路:

很明顯,這道題,我們需要從第一個位置開始找到一個連續的可參與運算的字符串(即這個字符串中的每個字符都在‘+-0123456789’中), 然後將這個字符串按加減法則進行運算。在這裏,我給出的一種方法是,在一個連續的加減序列中,最終的運算取決於最後一個字符是加還是減,所以只需要把這樣連續的一串字符替換成最後一個,就可以參與運算了。

代碼:

import re
class Solution:
    def myAtoi(self, str1: str) -> int:
        if not str1:
            return 0
            exit()
        elif len(str1) == 1:
            if str1[0] == '+' or str1[0] == '-':
                return 0
            exit()
        elif True:
            teststr = '+-0123456789'
            result = ''
            # 取出一個連續的可參與運算字符
            if teststr.find(str1[0]) != -1:
                for si in str1:
                    if si in teststr:
                        result += si
                    else:
                        break
            else:
                return 0
            # 替換連續+-
            result = re.sub('[+]+', '+', result)
            result = re.sub('[-]+', '-', result)
            result = re.sub('[-]*[+]*[-]', '-', result)
            result = re.sub('[+]*[-]*[+]', '+', result)
            if result[0] in ['-', '+']:
                result = '0' + result
            result = result.split('-')
            num = 0
            for i in range(len(result)):
                num = 0
                if '+' in result[i]:
                    result[i] = result[i].split('+')
                    for res in result[i]:
                        num = num + int(res)
                    result[i] = num
            num = int(result[0])
            for i in range(1, len(result)):
                num = num - int(result[i])
            return int(num) if int(num)>-2**31 and int(num) < 2**31-1 else -2**31
            
        

 

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