8. 字符串转换整数 (atoi)

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
        
                
    原文作者:cptn3m0
    原文地址: https://www.jianshu.com/p/fd5e9e6b7013
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞