1. 程式人生 > >演算法31--String to Integer (atoi)

演算法31--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.

沒啥意思,注意一下細節就可以了。

首先去除字串左邊的空格

字串為空  長度為1並且不是數字   第一個字元非正負號不是數字 則直接返回零

判斷正負號

從正負號之後的字元進行逐一判斷若是數字則記錄下來,若沒有數字則直接退出迴圈

檢查數字與int_max與int_min的大小關係,返回最終結果

class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        s = str.lstrip()
        #print(s)
        if len(s)==0:
            return 0
        if s[0]!='+' and s[0]!='-' and s[0].isdigit() is not True:
            return 0
        if len(s)==1 and (s[0]=='+' or s[0]=='-'):
            return 0
        flag = True
        start = 0
        if s[0]=='-':
            flag = False
        if s[0]=='-' or s[0]=='+':
            start = 1
        num = ''        
        for i in range(start, len(s)):
            if s[i].isdigit():
                num = num + s[i]
            else:
                break
        if num == '':
            return 0
        #print(num)
        intmax = pow(2,31)-1
        intmin = -pow(2,31)
        if flag:
            if int(num)>=intmax:
                return intmax
            else:
                return int(num)
        else:
            if -int(num)<=intmin:
                return intmin
            else:
                return -int(num)