[LeetCode][python3]0008. String to Integer (atoi)

class Solution:
def myAtoi(self, str: str) -> int:
str2=''
if not str:
return 0
for index,i in enumerate(str):
if i in ['1','2','3','4','5','6','7','8','9','0']:
break
elif i!=' ':
break
if i=='+':
index+=1
if i=='-':
str2+=i
index+=1
for i in range(index,len(str)):
if str[i] in ['1','2','3','4','5','6','7','8','9','0']:
str2+=str[i]
else:
break

if not str2 or str2=="-":
return 0
x=int(str2)
if x > 2147483648-1:
return 2147483648-1
elif x<-2147483648:
return -2147483648

return x
N2I -2020.03.15
class Solution:
def myAtoi(self, str: str) -> int:
num = ""
for char in str:
if num != "" and char in " +-":
break
if char in '1234567890-+':
num += char
elif char != " ":
break

if num in "+-":
return 0
else:
return min(max(int(num),-2**31),2**31-1)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store