atoi
字符转整数,每个题基本都有一些不同的输入,下面是一个LeetCode的模板
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if not str:
return 0
lst = list(str.strip()) # 剥去两边的空
sign = -1 if lst[0] == '-' else 1 # 判断是否有负号
if lst[0] in ['-', '+']:
del lst[0]
res, i = 0, 0
while i < len(lst) and lst[i].isdigit():
res = res * 10 + ord(lst[i]) - ord('0')
i += 1
return max(-2 ** 31, min(2 ** 31-1, res * sign))