8. String to Integer (atoi)

来源:互联网 发布:宿迁市12345网络问政 编辑:程序博客网 时间:2024/06/06 05:31

这里写图片描述

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        i = 0        sign = 1          base = 0        n = len(str)        INT_MAX = 2147483647        INT_MIN = -2147483648        a_0 = ord('0')        a_9 = ord('9')        while i < n and str[i] == ' ':#字符串前的空格            i += 1        if i < n and str[i] == '-':     #正负号            sign = -1            i += 1        elif i < n and str[i] == '+':            i += 1        while i < n and ord(str[i]) >= a_0 and ord(str[i]) <= a_9:          #判断是否超过字符串长度且判断当前的字符是不是非法字符            if base > INT_MAX / 10 or (base == INT_MAX / 10 and ord(str[i]) - a_0 > 7):#判断是否溢出                 return sign == 1 and INT_MAX or INT_MIN                             #大于最大值则返回INT_MAX,小于最小值返回INT_MIN            base = 10 * base + (ord(str[i]) - a_0)            i += 1        return base * sign
原创粉丝点击