看着挺简单,结果不断出错不断修改,就很容易绕晕了,用了一个小时四十分钟左右才完成。。。好慢哦:
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
a=str.lstrip()
if len(a)<1:
return 0
if len(a)==1:
if a[0] not in '0123456789':
return 0
else:
return int(a)
if a[0]!='-' and a[0]!='+' and a[0] not in '0123456789':
return 0
i=0
while i<len(a)-1:
if a[1:][i] not in '0123456789':
if a[:i+1]=='+' or a[:i+1]=='-' :
return 0
if int(float(a[:i+1]))>2**31-1:
return 2**31-1
elif int(float(a[:i+1]))<-2**31:
return -2**31
return int(float(a[:i+1]))
else:
i+=1
if int(float(a))>2**31-1:
return 2**31-1
elif int(float(a))<-2**31:
return -2**31
return int(float(a))
执行用时 :28 ms, 在所有 Python 提交中击败了72.82%的用户
内存消耗 :11.7 MB, 在所有 Python 提交中击败了35.29%的用户
执行用时为 8 ms 的范例
class Solution(object):
import re
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
return max(min(int(*re.findall('^[\+\-]?\d+',str.lstrip())),2**31 -1),-2**31)
* 表示是一个不定长的列表;
'^[\+\-]?\d+'
^ 匹配字符串的开头
[...]用来表示一组字符,单独列出:[amk]匹配'a','m'或'k'
re? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
\d 匹配任意数字,等价于[0-9]
re+ 匹配一个或者多个的表达式
——2019.10.11