Another 45 ms Python solution. Do we need to worry about int overflow in Python??


  • 0
    N
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            is_negative = False
            i = 0
            str = str.lstrip()
            if str.startswith('+'):
                i = 1
    
            if str.startswith('-'):
                is_negative = True
                i = 1
    
            result = 0
            while i < len(str):
                this_num = ord(str[i]) - ord('0')
                if this_num < 0 or this_num > 9:
                    break
    
                result *= 10
                result += this_num
                i += 1
    
            if is_negative:
                return max(-result, -2147483648)
               
            return min(result, 2147483647)
    

Log in to reply
 

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