请你来实现一个 atoi 函数,使其能将字符串转换成整数。(前两个我写的,效率不是很高)
class Solution(object):
def myAtoi1(self, s):
"""
:type s: str
:rtype: int
"""
temp = s.strip()
if not temp:
return 0
if temp[0].isalpha():
return 0
symbol_list = ["+", "-"]
ret_str = ""
for i in range(len(temp)):
if i == 0 and temp[i] in symbol_list:
ret_str += temp[i]
continue
if not temp[i].isdigit():
break
ret_str += temp[i]
ret_num = int(ret_str) if ret_str and ret_str not in symbol_list else 0
if -2 ** 31 < ret_num < 2**31:
return ret_num
else:
if ret_num > 0:
return 2**31 - 1
else:
return -2 ** 31
def myAtoi2(self, s):
"""
:type s: str
:rtype: int
"""
temp = s.strip()
if not temp:
return 0
if temp[0].isalpha():
return 0
symbol_list = ["+", "-"]
symbol = ""
start = 0
end = 0
for i in range(len(temp)):
if i == 0 and temp[i] in symbol_list:
symbol += temp[i]
start += 1
end += 1
continue
if not temp[i].isdigit():
break
end += 1
ret_num = int(symbol + temp[start: end]) if temp[start: end] else 0
if -2 ** 31 < ret_num < 2**31:
return ret_num
else:
if ret_num > 0:
return 2**31 - 1
else:
return -2 ** 31
def myAtoi(self, s):
"""这个代码写的漂亮"""
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
if __name__ == '__main__':
import re
s1 = Solution()
s = "3.14159"
print(s1.myAtoi(s))