45ms Python Solution


  • 0
    P
    class Solution(object):
        def myAtoi(self, str):
            num, sign, cur = 0, 1, 0
            while cur < len(str):
                if str[cur] == ' ':
                    cur += 1
                elif str[cur] == '-':
                    sign, cur = -1, cur+1
                    break
                elif str[cur] == '+':
                    cur += 1
                    break
                elif ord(str[cur]) > 57 or ord(str[cur]) < 48:
                    cur += len(str)
                else:
                    break
                
            while cur < len(str) and ord(str[cur]) >= 48 and ord(str[cur]) <= 57:
                if num > 214748364 or (num == 214748364 and ord(str[cur]) - 48 > 7):
                    if sign == 1:
                        return 2147483647
                    else:
                        return -2147483648
                num, cur = 10 * num + ord(str[cur]) - 48, cur+1
            
            return num * sign
    

Log in to reply
 

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