标签:
一、题目
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 characters 11 4>check range 12 """ 13 #null 14 if s == "": 15 return 0 16 17 #remove white space. 18 start = 0 19 while s[start] == " ": 20 start += 1 21 s = s[start:] 22 23 #check + and - 24 minusCount = 0 25 if s[0] == "-": 26 minusCount += 1 27 s = s[1:] 28 elif s[0] == "+": 29 s = s[1:] 30 elif s[0] >= "0" and s[0] <= "9": 31 pass 32 else: 33 return 0 34 35 #check other characters 36 rst = "" 37 38 for i in s: 39 if i >= "0" and i <= "9": 40 rst += i 41 else: 42 break 43 if rst == "": 44 return 0 45 46 #return results 47 if minusCount % 2 == 0: 48 if int(rst) <= 2147483647: 49 return int(rst) 50 else: 51 return 2147483647 52 else: 53 if int(rst) <= 2147483648: 54 return -int(rst) 55 else: 56 return -2147483648
四、总结
1.下午做完Reverse Integer,这个就熟练多了。
2.这题有个bug,但不算什么大问题。测试例“+-2”,返回结果是0.但是个人觉得应该返回-2.
3.晚安
标签:
原文地址:http://www.cnblogs.com/breada/p/4666087.html