Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
关于atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
直接把谷歌翻译粘过来:
该函数首先丢弃尽可能多的空白字符,直到找到第一个非空白字符。 然后,从这个字符开始,采用一个可选的初始加号或减号,后面跟随尽可能多的数字,并将其解释为一个数字值。
该字符串可以包含附加字符后面的那些形成整数的数字,这些字符被忽略,对这个函数的行为没有影响。
如果str中的第一个非空白字符序列不是有效整数,或者由于str为空或只包含空格字符而不存在这样的序列,则不执行转换。
如果不能执行有效的转换,则返回零值。 如果正确值超出了可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。
思路:
(1)跳过前面的空格、制表符等,可以用isspace()判断
(2)记录该数的正负
(3)遇到非数字字符后跳出循环并输出前面的数字
(4)边界:判断当前数字再升一位是否溢出,溢出则返回边界值。若不溢出先升位,再判断是否加当前位的值,加上不溢出则加上,溢出则输出边界。原因在于如果超出范围就返回最接近的 int 数。
1 class Solution(object): 2 def myAtoi(self, str): 3 INT_MAX = 2147483647 4 INT_MIN = -2147483648 5 sum = 0 6 sign = 1 7 i = 0 8 if str == ‘‘: 9 return 0 10 while i < len(str) and str[i].isspace(): #扫描的字符是空格/回车/制表符等 11 i += 1 12 if i < len(str) and str[i] == ‘-‘: 13 sign = -1 14 if i < len(str) and (str[i] == ‘-‘ or str[i] == ‘+‘): 15 i += 1 16 while i < len(str) and str[i].isdigit(): #扫描的字符是0~9的数字 17 digit = int(str[i]) 18 if INT_MAX / 10 >= sum: #INT_MAX/10 >= sum和INT_MAX - digit >= sum这两个判断条件确保了不会溢出。 19 sum *= 10 #此处是判断sum*10(当前的str[i]未加)是否溢出,不溢出则进行该操作 20 else: 21 if sign == 1: 22 return INT_MAX #否则输出边界值 23 else: 24 return INT_MIN 25 if INT_MAX - digit >= sum: #此处是判断sum+str[i]是否溢出,不溢出则加上,溢出则输出边界 26 sum += digit 27 else: 28 if sign == 1: 29 return INT_MAX 30 else: 31 return INT_MIN 32 i += 1 33 return sign * sum 34 35 if __name__==‘__main__‘: 36 s = ‘1‘ 37 solution = Solution() 38 print(solution.myAtoi(s))