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

简单分析

这个题目的题眼在于细节.
这个是分为阶段的

第一阶段

去除空格, 用python很容易处理.

str=str.strip()

处理'-'和'+'

        if str[0] == '-':
          is_negative = True
          str = str[1:]
        elif str[0] == '+':
          str = str[1:]
        
        if len(str) == 0:
          return 0

代码主体

最后的检查

        if is_negative == True:
          num = -num
        
        if num>2**31-1:
          num = 2**31-1
        elif num < -1* 2**31:
          num = -1*2**31

完整的代码

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        
        # guard
        
        str = str.strip()
        num = 0
        is_negative = False
        
        if len(str) == 0:
          return 0
        
        
        if str[0] == '-':
          is_negative = True
          str = str[1:]
        elif str[0] == '+':
          str = str[1:]
        # guard 
        # check again
        if len(str) == 0:
          return 0
        
        
        for c in str:
          if c.isdigit() == False:
            break
          num = int(c)+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


你可能感兴趣的:(8. 字符串转换整数 (atoi))