8. 字符串转换整数 (atoi)
2019-03-10 本文已影响0人
cptn3m0
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
if len(str) == 0:
return 0
is_negative = False
num = 0
if str[0] == '-':
is_negative = True
str=str[1:]
elif str[0] == '+':
str=str[1:]
if(len(str)==0):
return 0
for ch in str:
if ch.isdigit() == False:
break
num = int(ch)+num*10
if is_negative == True:
num = -num
if num >2**31-1:
num = 2**31-1;
elif num < -1*2**31:
num = -1*2**31
return num