In the question, it is mentioned that it is vague and we need to make all the possible input cases and expected solutions. Before going into solution, try to figure out outcomes of these test cases :
- " +10 "
- " +001313"
- " +a"
- " -12a12"
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ if len(str) == 0 : return 0 # flags ans = 0 number_started = False sign = 1 signflag = False # for each character in input stirng for i in str : # if character is empty space, and the number is not started then continue else break(we got the number) if i == ' ': if number_started == False: continue else: break # if character is a sign and the number is not yet started then save the sign elif (i=='-' or i=='+') and number_started == False and signflag == False: sign = -1 if i=='-' else 1 signflag = True number_started = True # if the character is a number in between 0 to 9 then add it to answer at units digits by shifting already available digits in ans to left elif ord(i) >= 48 and ord(i) <= 57 : number_started = True ans = (ans * 10) + (ord(i) - ord('0')) # if none of above conditions satisfy then break out of loop. else: break # check for integer overflow if ans >= 2**31 : ans = 2**31 if sign == 1: return ans - 1 else : return sign * ans return sign * ans