String to Integer (ATOI) - Python solution


  • 2
    S

    Here is my solution to the problem. It takes care of all the edge cases as well.

    class Solution:
        def myAtoi(self, str):
            res = 0 # to store the result number
            sign = 1 # to keep track of the sign of the number
            i = 0 # index variable
            
            # Edge cases which don't have a valid digit as part of the string should return 0
            if len(str) is 0: 
                return 0
            if len(str) is 1 and str[0] == '+': 
                return 0
            elif len(str) is 1 and str[0] == '-':
                return 0
            
            # To handle whitespaces, simply bypass the characters until a valid character is encountered.  
            # Keep incrementing the index variable i as we skip whitespaces
            if str[0] == ' ':
                while str[i] == ' ':
                    i += 1
                    
            # Handle the sign character if present
            if str[i] == '-':
                sign = -1
                i += 1
            elif str[i] == '+':
                sign = 1;
                i += 1
                
            # Loop through the string to identify the number
            for j in range(i,len(str)):
                # Return result number if we encounter an invalid character, say another sign or non-numric character
                # Also keep track of result to ensure the result doesn't exceed the MAX_INT & MIN_INT values
                if str[j] not in ['0','1','2','3','4','5','6','7','8','9']:
                    if res > 2147483647 and sign == 1:
                        return sign*(2147483647)
                    elif res > 2147483647 and sign == -1:
                        return -2147483648
                    return sign*res
                
                # For valid digits, keep incrementing the result & shifting the power bit
                res = res*10 + (ord(str[j]) - ord('0'))
                
                # After reading full valid string, return result as above
                if res > 2147483647 and sign == 1:
                        return sign*(2147483647)
                elif res > 2147483647 and sign == -1:
                        return -2147483648        
            return sign*res
    

Log in to reply
 

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