一、题目
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.
二、解析
本题是指将字符串中的连续数字输出出来,需要考虑多种情况:
1>空字符串、无数字,返回0
2>前边多余空格," 1234",返回1234
3>有正负符号的," -234",返回-234
4>有其他无效字符的,保留之前数字结果," -234&(90123",返回-234
5>大于32bit范围,返回题目要求
三、代码
1 class Solution: 2 # @param {string} str 3 # @return {integer} 4 def myAtoi(self, s): 5 """ 6 1.null, return 0 7 2.not null: 8 1>white space 9 2>check + and -10 3>check other characters11 4>check range12 """13 #null14 if s == "":15 return 016 17 #remove white space.18 start = 019 while s[start] == " ":20 start += 121 s = s[start:]22 23 #check + and -24 minusCount = 025 if s[0] == "-":26 minusCount += 127 s = s[1:]28 elif s[0] == "+":29 s = s[1:]30 elif s[0] >= "0" and s[0] <= "9":31 pass32 else:33 return 034 35 #check other characters36 rst = ""37 38 for i in s:39 if i >= "0" and i <= "9":40 rst += i41 else:42 break43 if rst == "":44 return 045 46 #return results47 if minusCount % 2 == 0:48 if int(rst) <= 2147483647:49 return int(rst)50 else:51 return 214748364752 else:53 if int(rst) <= 2147483648:54 return -int(rst)55 else:56 return -2147483648
四、总结
1.下午做完,这个就熟练多了。
2.这题有个bug,但不算什么大问题。测试例“+-2”,返回结果是0.但是个人觉得应该返回-2.
3.晚安