python solution with explanation


  • 0
    A
    
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            #delete blank space in the front of the string
            #the input could be unicode, use list to change it to ascii
            input=list(str.strip())
            if not input:
                return 0
            sign = -1 if input[0]=='-' else 1
            if input[0] in ['-','+']:
                del input[0]
            
            ans=0
            for token in input: 
                #if it is not valid input, i.e. -+32, or -$%32, break and return 0
                if token.isdigit():
                    ans = ans*10 + int(token)-int('0')
                else:
                    break
            #for overflow, return min or max integer
            return max(-2**31, min( 2**31-1,ans*sign))
    
    
    
    
    
    
    

Log in to reply
 

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