首页 > 代码库 > String to Integer (atoi)

String to Integer (atoi)

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.

spoilers alert... click to show requirements for atoi.

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.

分析:

字符串转整数。这个问题如果用C/C++来做,代码可以写得很漂亮,用Python就略有些难看。一个比较诡异的地方是即使Python没有最大最小整数限制,这个题目仍然要求处理溢出的情况。这在Python里面也就是最后添加两个判断,但是对于C/C++语言来说需要额外处理好。

class Solution:    INT_MAX = 2147483647    INT_MIN = -2147483648    # @return an integer    def atoi(self, str):        if not str or len(str) == 0:            return 0        i = 0        while str[i] ==  :            i += 1        val = 0        sign = False        if str[i] == -:            sign = True            i += 1        elif str[i] == +:            i += 1        for i in range(i, len(str)):            c = str[i]            if 0 <= c <= 9:                val = val * 10 + (ord(c) - ord(0))            else:                break        if sign:            val = -val            val = max(val, Solution.INT_MIN)        else:            val = min(val, Solution.INT_MAX)        return valif __name__ == __main__:    s = Solution()    assert s.atoi(1234) == 1234    assert s.atoi(-347) == -347    assert s.atoi(+-2) == 0    assert s.atoi(+1) == 1    assert s.atoi( 010) == 10    assert s.atoi(2147483648) == 2147483647    assert s.atoi(-2147483648) == -2147483648    print PASS

小结:

C语言可以用指针,Python里面我尽量仿照C的实现,用数组下标代替,不需要回溯,只要处理好各种异常情况。

String to Integer (atoi)