My python solution, cost 68ms.


  • 8
    W
    class Solution:
        # @return an integer
        def atoi(self, str):
            str = str.strip()
            if len(str) == 0:
                return 0
            tmp = "0"
            result = 0
            i = 0
            if str[0] in "+-":
                tmp = str[0]
                i = 1
            MAX_INT = 2147483647
            MIN_INT = -2147483648
            for i in xrange(i, len(str)):
                if str[i].isdigit():
                    tmp += str[i]
                else:
                    break
            if len(tmp) > 1:
                result = int(tmp)
            if result > MAX_INT > 0:
                return MAX_INT
            elif result < MIN_INT < 0:
                return MIN_INT
            else:
                return result
    

    At first, I remove all whitspaces by using strip() function. Then, we should know only one operator is allowed, if there are two operator, for example, "+-2", the input is invalid for atoi() function, 0 should be returned. And we should put as many as possible numerical value into the 'tmp' string. If the length of 'tmp' is 1, it means the 'tmp' is '0' or '+' or '-', and we should return 0 in the function. If the length of 'tmp' is greater than 1, it means the 'tmp' is '0...(numbers)' or '+...(numbers)' or '-...(numbers)', then we can use integer force conversion to make 'tmp' to an integer. At last, If the result is out of the range of representable values, MAX_INT (2147483647) or MIN_INT (-2147483648) is returned.


  • 5
    M

    Well - you did an amazing job there around catching exceptions and corner case ; but I guess I would still have to disagree with you type casting the string to an integer directly . Part of the challenge is to covert the string to int by hand ( manually )


Log in to reply
 

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