Cheating with int():
class Solution:
# @return an integer
def atoi(self, str):
str = str.strip()
newStr = []
for i in range(len(str)):
if '0' <= str[i] <= '9' or (str[i] in ('+', '-') and i == 0):
newStr.append(str[i])
else:
break
if newStr in ([], ['+'], ['-']):
return 0
elif -2147483648 <= int(''.join(newStr)) <= 2147483647:
return int(''.join(newStr))
elif int(''.join(newStr)) > 2147483647:
return 2147483647
else:
return -2147483648
Without cheating:
class Solution:
# @return an integer
def atoi(self, Str):
dic={"0":0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
rst=0
validset='+-0123456789'
numberset='0123456789'
INT_MAX="2147483647"
INT_MIN="2147483648"
Str=Str.lstrip(' ')
for i in range(len(Str)):
if Str[i] not in validset:
Str=Str[:i]
break
if (len(Str)==1 and Str in '+-') or ('-' in Str[1:] or '+' in Str[1:]) or len(Str)==0:
return 0
sign=1
if Str[0]=='-':
sign=-1
Str=Str[1:]
elif Str[0]=='+':
Str=Str[1:]
if len(Str)>10:
return -2147483648 if sign==-1 else 2147483647
elif len(Str)==10:
overflow=True
if sign==-1:
for i in range(10):
if Str[i]<INT_MIN[i]:
overflow=False
break
if overflow:
return -2147483648
else:
for i in range(10):
if Str[i]<INT_MAX[i]:
overflow=False
break
if overflow:
return 2147483647
for i in range(len(Str)):
if sign==1:
rst+=dic[Str[i]]*(10**(len(Str)-i-1))
else:
rst-=dic[Str[i]]*(10**(len(Str)-i-1))
return rst
else:
for i in range(len(Str)):
rst+=dic[Str[i]]*(10**(len(Str)-i-1))
return rst*sign
No comments :
Post a Comment