# 60ms python solution; OJ says this beats 100% python submissions

• ``````class Solution(object):
def myAtoi(self, s):
"""
:type str: str
:rtype: int
"""
###better to do strip before sanity check (although 8ms slower):
#ls = list(s.strip())
#if len(ls) == 0 : return 0
if len(s) == 0 : return 0
ls = list(s.strip())

sign = -1 if ls[0] == '-' else 1
if ls[0] in ['-','+'] : del ls[0]
ret, i = 0, 0
while i < len(ls) and ls[i].isdigit() :
ret = ret*10 + ord(ls[i]) - ord('0')
i += 1
return max(-2**31, min(sign * ret,2**31-1))``````

• I think there's a problem. If the case is " ", the list index will go out of range in "sign = -1 if ls[0] == '-' else 1".

• Thanks @xinyi4, you are right. I have added comment to my code above saying better to do strip before sanity check, although this makes my code 8ms slower (68ms now).

• @zcjsword

``````while i < len(ls) and ls[i].isdigit() :
ret = ret*10 + ord(ls[i]) - ord('0')
i += 1
return max(-2**31, min(sign * ret,2**31-1))
``````

This part looks like Java code.

``````while (i < ls.length() && ls.charAt(i).isDigit()) {
ret = ret * 10 +  (ls.charAt(i) - '0');
i++;
}
return Math.max(-2147483648, Math.min(sign * ret, 2147483647))``````

• @zcjsword Hi I think you can simply change to this
def myAtoi(self,s):
ls = list(s.strip())
if len(ls) == 0: return 0

• O(n) space. Should be O(1)

• @xinyi4 if len(s) == 0: return 0

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