Simple Python solution that beats 98.25% answers


  • 1
    G

    Things to be careful with:
    1. When there are two signs, return 0
    2. When there is a space after a a number or a sign , return 0
    3. Pay attention to the maximum value

    class Solution:
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            result = 0 
            hasSign = False
            hasNum = False
            sign = 1
            for s in str:
                c = ord(s)
                if  c >= 48 and c <= 57:
                    result = result * 10 + ord(s) - 48
                    hasNum = True
                elif s == "-":
                    if not hasSign:
                        sign = -1
                    else:
                        return 0
                    hasSign = True
                elif s == "+":
                    
                    if hasSign:
                        return 0
                    hasSign = True
                elif s ==" ":
                    if not hasNum and not hasSign:
                        continue
                    else:
                        break
                else:
                    break
                    
            num = result * sign
            MAX_INT = 2147483647
            MIN_INT = -2147483648
            if num > MAX_INT > 0:
                return MAX_INT
            elif num < MIN_INT < 0:
                return MIN_INT
            else:
                return num
    

Log in to reply
 

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