题目说明
Implement atoi which converts a string to an integer.
题目可以简短概括为将一个输入的字符串转化为数值型输出,其中特殊情况有:
1.首字符可以是空格/数字/正负符号(有效输入为多空格直至出现后面两种情况之一)
2.首字符一旦不是上述三种情况之一直接返回0
3.最后输出的数值有32位有符号整数值范围限制
4.连续‘±’或‘-+’情况则视为无效输出返回0
总结:本题没有任何逻辑或者是技术上的难度
(个人水平有限,一直在通过各种if判断来裁定边界情况)
代码部分1
class Solution:
def myAtoi(self, str: 'str') -> 'int':
c=1
oc = -1
out = ''
for i in str:
if i==' ' or i=='-' or i=='+' or (i >='0' and i <= '9'):
#print('ok')
if oc>0:
if (i<'0' or i>'9'):break
if i=='-':
c=-1
oc=1
continue
if i=='+':
c=1
oc=1
continue
if i >='0' and i <= '9':
out += i
oc=1
continue
else:break
if oc<0 or out=='':
return 0
else:
out = c*int(out)
if out<-2**31:
return -2**31
elif out>2**31-1:
return 2**31-1
else:
return out
Runtime: 56 ms, faster than 98.53% of Python3 online submissions for String to Integer (atoi).
Memory Usage: 12.6 MB, less than 37.95% of Python3 online submissions for String to Integer (atoi).
emmm解题思路不做评价
代码部分2
class Solution:
def myAtoi(self, str):
ret = re.search('^(([+|-]\d+)|\d+)',str.strip())
#strip移除字符串头尾指定的字符序列(默认为空格或换行符)
#search在字符串中寻找模式匹配(返回第一个匹配)
#^放在开头表示后续匹配内容必须是以要求匹配模式开头的字符串
#+表示多个字符
#[+|-]\d+表示+或者-带一堆数字
#\d+纯一堆数字
if ret:
ret = ret.group()
ret_int = int(ret)
else:
ret_int = 0
if ret_int > 2147483647:
ret_int = 2147483647
elif ret_int < -2147483648:
ret_int = -2147483648
return ret_int
Runtime: 52 ms, faster than 100.00% of Python3 online submissions for String to Integer (atoi).
Memory Usage: 12.6 MB, less than 45.68% of Python3 online submissions for String to Integer (atoi).
思路解析:
大佬就是大佬
还有正则表达式真的是强者一般的存在!!!