Share my Python Solution with 6 branches


  • 0
    Z
    class Solution(object):
        def myAtoi(self, str):
            flag = False
            begin = False
            final = 0
            INT_MAX = 2147483647
            INT_MIN = -2147483648
            for i in range(len(str)):
                if str[i] == '-' and not begin:
                    begin = True
                    flag = True
                elif str[i] == '+' and not begin:
                    begin = True
                elif ord('0') <= ord(str[i]) and ord(str[i]) <= ord('9'):
                    begin = True
                    final = ord(str[i]) - ord('0') + final * 10
                    if final > INT_MAX and not flag:
                        return INT_MAX
                    elif flag and final < INT_MIN:
                        return INT_MIN
                elif not begin and str[i] == ' ':
                    continue
                elif begin and final != 0 and (ord('0') > ord(str[i]) or ord(str[i]) > ord('9')):
                    return -final if flag else final
                else:
                    return 0
            return -final if flag else final

  • 0

    a little typo, should be:

       if final > INT_MAX and not flag:
                  return INT_MAX
       elif flag and final > INT_MAX:
                  return INT_MIN

Log in to reply
 

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