Simple and straightforward python solution with explanation


  • 2
    F

    Simple strip the leading and trailing space, and then discuss different cases of the character. Use a flag to indicate the sign of the output. Return the output once we hit a space or alphabetical character. If there are more than two sign characters, return 0.

    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            s=str.strip()
            sign = 1
            res = 0
            cnt = 0
            for i in xrange(len(s)):
                cur = s[i]
                if cur == '+': 
                    sign = 1
                    cnt += 1
                elif cur == '-': 
                    sign = -1
                    cnt += 1
                elif cur.isdigit():
                    res = 10*res + (ord(cur) - ord('0'))
                elif cur.isalpha() or cur == ' ':
                    break
                if cnt > 1: return 0
        return max(min(res*sign, 2147483647), -2147483648)

Log in to reply
 

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