LeetCode8: string to integer (atoi)

Please implement an atoi function to convert strings to integers.

First, the function discards the useless start space characters as needed until the first non space character is found.

When the first non empty character we find is a positive or negative sign, we will combine the symbol with as many consecutive numbers as possible as the sign of the integer; if the first non empty character is a number, we will directly combine it with consecutive number characters to form an integer.

In addition to the valid integer part of the string, there may be extra characters, which can be ignored and should not affect the function.

Note: if the first non whitespace character in the string is not a valid integer character, the string is empty, or the string contains only whitespace characters, your function does not need to be converted.

In any case, return 0 if the function does not perform a valid conversion.

Ideas: 1. First judge the positive and negative difference record + - sign
2. Read the list one by one
3. Output list and add sign

``````class Solution:
def myAtoi(self, str):
str=str.lstrip()                #Remove left space
num="0123456789"                #number
symbol={'-':-1,'+':1}           #Attached number
if len(str)==0: return 0
res_lst=[]
res_int=0
sign=1
flag=True
if str[0] in symbol:           #Get + - No.
sign=symbol[str[0]]
elif str[0] in num:            #Direct listing of figures
res_lst.append(str[0])
else:
return 0
i=1
while i<len(str) and flag:     #loop
if str[i] in num:
res_lst.append(str[i]) #Direct listing of figures
i=i+1
else:
flag=False

if len(res_lst)>0:
res_int=int("".join(res_lst))*sign
INT_MAX=2**31-1                        #Digital overflow check
INT_MIN=-2**31
if res_int>INT_MAX: return INT_MAX
if res_int<INT_MIN: return INT_MIN
return res_int                        #Return correct value
else:
return 0

print(Solution().myAtoi('   -42'))
print(Solution().myAtoi('words and 987'))``````

Posted on Sun, 09 Feb 2020 06:34:43 -0800 by ednark