Solution for atoi using python


  • 0
    class Solution(object):
        def myAtoi(self, s):
            i = 0
            sign = '+'
            number_of_digits = 0
            
            #If string is empty return 0
            if not s:
                return 0
            
            #Remove all the spaces or 0's in the starting of the input string
            while(s[i] == ' ' or s[i] == '0'):
                i += 1
                
            #To keep track of the number of '+' or '-' signs
            count = 1
            
            #Find the number of '+' or '-' sign and count the number of signs
            while((i < len(s)) and (s[i] == '+' or s[i] == '-')):
                if(s[i] == '-'):
                    sign = '-';
                count += 1
                i += 1
            
            #If there are two or more '+' or '-' sign or 
            #we have reached the length of the string or 
            #next character is not a numeric one return 0
            if(i == len(s) or (s[i] < '0' or s[i] > '9') or count > 2):
                return 0
            
            ln = len(s) - 1
            base = ord('0')
            
            result = 0
            
            #To get the value of the number before the first character
            while(i <= ln):
                if(s[i] < '0' or s[i] > '9'): 
                    break;
                temp = ord(s[i]) - base
                result = temp + result * 10
                i += 1
                
            #For handling the largest and minimum value according to C compiler
            
            if(result > 2147483647 and sign == '+'):
                result =  2147483647
            if(result > 2147483648 and sign == '-'):
                result =  2147483648
            
            if(sign == '-'):
                result = -result;
            return result
    

Log in to reply
 

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