Nice atoi python 3 solution


  • 0
    I
    class Solution:
        def myAtoi(self, str):
            """
            We use the ascii code to check if a character is a digit.
            Ascii codes for digits goes from 48 for Zero, and 57 for Nine.
            Also check some special cases, input is null or empty, string has sign, 
            string has other characters than digits, the result number is bigger that integer.
            :type str: str
            :rtype: int
            """
            if str == None or str == '':
                return 0
    
            n     = 0
            str   = str.strip().replace( ',', '' )
            start = 0
            sign  = 1
            if str[ 0 ] == '-' or  str[ 0 ] == '+':
                start = 1
            if str[0] == '-':
                sign = -1
    
            for i in range( start, len(str) ):
                a = ord( str[ i ] )
                if a >= 48 and a <= 57:
                    # we have a digit
                    d = a - 48
                    n = n*10 + d
                else:
                    # we found a character that is not a digit
                    break
            n = sign * n
    
            if n < -2147483648:
                return -2147483648
            if n > 2147483647:
                return 2147483647
    
            return n
    
    

Log in to reply
 

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