由于开始准备找工作了,之前曾经花6天,每天刷11题的方式迅速刷完了牛客网的剑指OFFER66题,但是很快就忘记了,想想自己虽然菜,但是也可以刷刷Leetcode简单题吧,这篇算是第一篇把。
这道题目看起来貌似不是很麻烦,但是实际上处理起来特别的麻烦,题意也没说清:
情况1. 比如遇到“+-12” 两个符号都出现了。这种就凉了
情况2. 比如遇到“-5-” 那么这时候应该输出的是-5 但是如果遇到的是“-5 20”那应该输出什么呢?0还是-5?
情况3 边界问题的考虑,这个比较简单
总之,在多次错误之后,终于通过了。下面贴上我的Python代码
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
num = 0
fla = False
could = False
min = 1
hasnumber = False
issplit = False
for st in str:
if st == ' ' :
if hasnumber: issplit = True
continue
if st == '-':
if hasnumber: break
hasnumber = str
min = -1
continue
if st == '+':
if hasnumber: break
fuhao = True
hasnumber = True
continue
if st <= '9' and st >= '0':
if issplit: break
num = num * 10 + ord(st) - ord('0')
fla = True
could = True
hasnumber = True
continue
else:
if not could: return 0
if fla: break
total = num * min
if total < -pow(2,31): return -2147483648
if total > pow(2,31)-1: return pow(2,31)-1
return total