String to Integer (atoi)(python)

来源:互联网 发布:python股票交易策略 编辑:程序博客网 时间:2024/05/21 17:19

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
注意如果超出范围就返回最接近的 int 数。eg:2147483648 大于 INT_MAX(2147483647) ,就返回 2147483647 。
要注意几点:跳过前面的空格,\t,\n;范围界定

class Solution:  

    # @return an integer  
    def myAtoi(self, str):  
        str = str.strip()  
        if not str:  
            return 0  
 
        MAX_INT = 2147483647  
        MIN_INT = -2147483648  
        ret = 0  
        overflow = False  
        pos = 0  
        sign = 1  
 
        if str[pos] == '-':  
            pos += 1  
            sign = -1  
        elif str[pos] == '+':  
            pos += 1  
 
        for i in range(pos, len(str)):  
            if not str[i].isdigit():  
                break  
            ret = ret * 10 + int(str[i])  
            if not MIN_INT <= sign * ret <= MAX_INT:  
                overflow = True  
                break  
 
        if overflow:  
            return MAX_INT if sign == 1 else MIN_INT  
        else:  

            return sign * ret


0 0
原创粉丝点击