Python solution based on RegEx


  • 16
    G
    class Solution:
        # @return an integer
        def atoi(self, str):
            str = str.strip()
            str = re.findall('(^[\+\-0]*\d+)\D*', str)
    
            try:
                result = int(''.join(str))
                MAX_INT = 2147483647
                MIN_INT = -2147483648
                if result > MAX_INT > 0:
                    return MAX_INT
                elif result < MIN_INT < 0:
                    return MIN_INT
                else:
                    return result
            except:
                return 0

  • 0
    F

    Does this line of code "str = re.findall('(^[+-0]\d+)\D', str)" mean that if the string contains characters like "(^[+-0]\d+)\D", it will return an empty string?


  • 0
    F

    If the line of code "str = re.findall('(^[+-0]\d+)\D', str)" mean that it returns an empty string if the characters like '(^[+-0]*\d+)\D', why there are "0", "+" and "-" in there? So confused!


  • 0
      I think the following RegEx sentence can be changed to
       From :(^[\+\-0]*\d+)\D*
       To       :(^[\+\-0]*\d+)
       Of course your code is also right! 
    

  • 0
    A

    isn't this just casting the string back to a number?


  • 2

    @Google

    Let me simplify the answer -

        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            str = str.strip()
            str = re.findall('^[+\-]?\d+', str)
    
            try:
                res = int(''.join(str))
                MAX = 2147483647
                MIN = -2147483648
                if res > MAX:
                    return MAX
                if res < MIN: 
                    return MIN
                return res
            except: 
                return 0

  • 0
    Y

    @zzhai said in Python solution based on RegEx:

    ^[+-]?\d+

    Hi, I'm new to python and I'm confused by this "^[+-]?\d+"
    How exactly does this work? Thanks


  • 2
    C

    @yxyang this is called regular expression, details in python doc .
    The whole expression is (^[\+\-0]*\d+)\D*, where ^ matches the beginning of the string, [] matches any single character inside the bracket, * means preceding character [\+\-0] can be matched zero or more times, \d means decimal digits, + means preceding character \d must appear at least once, \D means nondigits.


  • 0
    I

    class Solution(object):
    def myAtoi(self, str):
    """
    :type str: str
    :rtype: int
    """
    if not str:
    return 0
    INT_MAX = 2147483647
    INT_MIN = -2147483648
    import re
    newstr=""
    match = re.search("^[+-]{0,1}[0-9]+",str.strip())

        if match:
            newstr=int(match.group())
            if(INT_MIN  < newstr < INT_MAX ):
                return newstr
            else: 
                if newstr <= INT_MIN :
                    return INT_MIN
                else:
                    return INT_MAX
        return 0

  • 0
    D

    @Google I came up with a very similar one, but I did the char to int conversion manually...

    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            import re
            p=re.compile('\s*([+-]?)(\d*)')
            n=p.match(str)
            
            if n.group(1)=='-':
                sign = -1
            else:
                sign = 1
                
            number=0
            for i in range (0,len(n.group(2))):
                number=number*10+(ord(n.group(2)[i])-ord('0'))
                
            number=number*sign
            
            if (number>2147483647):
                number=2147483647
            if (number<-2147483648):
                number=-2147483648
            
            return number

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.