49ms Python AC Solution Beats 100%


  • 0
    1. Note that there are upper bound and lower bound for output.
    2. This problem is all about test cases. Solve tricky cases such as:
      "a123c" -> 0
      "+-123" -> 0
      " 123c" -> 123
      "1-23" -> 1
      "+ 23" -> 0
      ...
      etc.
    class Solution(object):
        def myAtoi(self, s):
            res, sign, cur = 0, 1, 0
    
            while cur < len(s):
                if s[cur] == ' ':
                    cur += 1
                elif s[cur] == '-':
                    sign, cur = -1, cur+1
                    break
                elif s[cur] == '+':
                    cur += 1
                    break
                elif ord(s[cur]) > 57 or ord(s[cur]) < 48:
                    cur += len(s)
                else:
                    break
    
            while cur < len(s) and ord(s[cur]) <= 57 and ord(s[cur]) >= 48:
                res, cur = res*10+(ord(s[cur])-48), cur+1
                
            res *= sign
    
            return min(res, 2147483647) if res > 0 else max(res, -2147483648)
    

Log in to reply
 

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