56 ms python solution without try


  • 0
    L

    Steps:

    1. remove head spaces
    2. handle ""
    3. handle string whose head char is not valid
    4. skip first char and stop loop if char is not a digit
    5. handle "+" "-"
    6. handle overflow
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            new_str = str.lstrip()
            if len(new_str) == 0:
                return 0
            if not (new_str[0] in "+-" or ('0' <= new_str[0] <= '9')):
                return 0
    
            end = 0
            for i in xrange(len(new_str)):
                if i == 0:
                    end = i + 1
                    continue
                char = new_str[i]
                if not ('0' <= char <= '9'):
                    break
                end = i + 1
    
            num_str = new_str[:end]
            if num_str in "+-":
                return 0
    
            num = int(num_str)
            if num < -2147483648:
                return -2147483648
            elif num > 2147483647:
                return 2147483647
            else:
                return num
    

Log in to reply
 

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