将字符串转换成整数

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.

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

分析:

  这道题难度不大,只需要把可能出现的情况考虑进去就行了。

class Solution(object):
    def __init__(self):
        self.max_int = pow(2,31)-1
        self.min_int = pow(2,31)  # abs value, without sign
        self.max_str = str(self.max_int)
        self.min_str = str(self.min_int)
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str_tmp = str.strip()
        sign = 1
        value_str = ''
        for i in range(len(str_tmp)):
            if i ==  0 and str_tmp[i] == '-':
                sign = -1
            elif i == 0 and str_tmp[i] == '+':
                sign = 1
            elif str_tmp[i] < '0' or str_tmp[i] > '9':
                break
            else:
                value_str += str_tmp[i]
            if sign == -1 and (len(value_str) > len(self.min_str) or len(value_str) == len(self.min_str) and value_str >= self.min_str):
                return sign*self.min_int
            if sign == 1 and (len(value_str) > len(self.max_str) or len(value_str) == len(self.max_str) and value_str >= self.max_str):
                return self.max_int
        res = 0
        for i in range(len(value_str)):
            res  = res*10 + int(value_str[i])
        return res*sign
原文地址:https://www.cnblogs.com/Peyton-Li/p/7650772.html