Simple python solution 76ms


  • 0
    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
    M

    Well - you caught the corner cases ; by defining the MAX_INT and MIN_INT - but you sort of directly casted it to an int. the real challenge is to not use "int" directly .


  • 0
    G

    I know this is kind of a hacky way of doing it, but this is what you want in production code - clean and easy (well maybe not, because you should use existing libraries, lol). As to the maxint and minint, it is because the maxint and minint defined in Python (sys.maxint and -sys.maxint-1) are different than the one int the test case.


  • 0
    M

    true ! a ton of problems get trivialized especially when you use python ( for example , there is a problem that asks you to search in a rotated array ) ; if you use "in" - it gives the same logarithmic complexity for both rotated and unrotated arrays. Also also Median of two sorted arrays - python programmers can get away by using something like sorted(A+B) and returning the middle element !


  • 0
    M

    BTW - I have solved a few of the problems that way too :P & am guilty of the same .


Log in to reply
 

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