Python 3 solution:


  • 1
    S

    4 steps:
    1.Find the first character which is not space, the rest of string store in str2.
    2.Check if the character is '+' or '-', store it in indicator.
    3.Calculate the following character until the one is not in 0-9.
    4.Return the result
    .
    '''
    class Solution:
    def myAtoi(self, str):

        INT_MAX = 2147483647
        INT_MIN = -2147483648
        indicator = 1
        result = 0               
        firstNotSpaceIndex = 0
        for firstNotSpaceIndex, i in enumerate(str):
            if i != ' ':
                break
        str2 = str[firstNotSpaceIndex:]
        for index, i in enumerate(str2):
            if i == '+' or i == '-':
                if i == '-':
                    indicator = -1
                if index < len(str2) - 1:
                    index += 1
                else:
                    return 0
            while str2[index] >= '0' and str2[index] <= '9': 
                result = result*10 + (int(str2[index]));                
                if result*indicator >= INT_MAX:
                    return INT_MAX
                if result*indicator <= INT_MIN:
                    return INT_MIN             
                if index < len(str2) - 1:
                    index += 1
                else:
                    break
            break
        return result*indicator    
    

    '''


Log in to reply
 

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