leetcode -. 8 integer string conversion (atoi)

Looking very simple, the results continue to wrong continuously changing, and it is easy around the halo, and spent an hour four minutes to complete. . . Oh, very slow:

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        a=str.lstrip()
        if len(a)<1:
            return 0
        if len(a)==1:
            if a[0] not in '0123456789':
                return 0
            else:
                return int(a)

        if a[0]!='-' and a[0]!='+' and a[0] not in '0123456789':
            return 0
        i=0
        while i<len(a)-1:
            if a[1:][i] not in '0123456789':
                if a[:i+1]=='+' or a[:i+1]=='-' :
                    return 0
                if int(float(a[:i+1]))>2**31-1:
                    return  2**31-1
                elif int(float(a[:i+1]))<-2**31:
                    return  -2**31 
                return int(float(a[:i+1]))
            else:
                i+=1
        if int(float(a))>2**31-1:
            return 2**31-1
        elif int(float(a))<-2**31:
            return  -2**31
        return int(float(a))
When execution: 28 ms, beat the 72.82% of all users in Python submission
Memory consumption: 11.7 MB, defeated 35.29% of all users in Python submission
When the execution is 8 MS paradigm
 class Solution (Object):
     Import Re
     DEF myAtoi (Self, str):
         "" "
        :type str: str
        :rtype: int
        """
        return max(min(int(*re.findall('^[\+\-]?\d+',str.lstrip())),2**31 -1),-2**31)

* Denotes a variable length list;
'^ [\ + \ -] \ + D?'
^ Matches the beginning of the string
[...] is used to represent a set of characters, listed separately: [amk] matches 'a' , 'm' or 'K'
Re? 0, or a match from the previous segment defined regular expression, non-greedy manner
\ d match any number, is equivalent to [0-9]
Re + matches one or more of expression

                                                                                                           ——2019.10.11

 

 

 

 

 

 
 
 

Guess you like

Origin www.cnblogs.com/taoyuxin/p/11655542.html