美文网首页LeetCode
Python字符串转换整数 (atoi)

Python字符串转换整数 (atoi)

作者: GhostintheCode | 来源:发表于2018-12-06 22:08 被阅读0次

    Python字符串转换整数 (atoi)


    题目:

    实现 atoi,将字符串转为整数。

    提示:仔细考虑所有输入情况。如果你想挑战自己,请不要看下面并自己考虑所有可能的输入情况。

    说明:这题解释的比较模糊(即没有指定输入格式)。你得事先汇集所有的输入情况。

    atoi的要求:

    这个函数需要丢弃之前的空白字符,直到找到第一个非空白字符。之后从这个字符开始,选取一个可选的正号或负号后面跟随尽可能多的数字,并将其解释为数字的值。
    字符串可以在形成整数的字符后包括多余的字符,将这些字符忽略,这些字符对于函数的行为没有影响。
    如果字符串中的第一个非空白的字符不是有效的整数,或者没有这样的序列存在,字符串为空或者只包含空白字符则不进行转换。
    如果不能执行有效的转换,则返回 0。如果正确的值超过的可表示的范围,则返回 INT_MAX(2147483647)或 INT_MIN(-2147483648)。

    解法

    这道题的难点在于如何将所有可能输入的情况覆盖到。
    题目中包括的:
    任意地方的空白字符‘ ’
    跳过任意地方的非数字字符
    数值范围限制(INT_MAX or INT_MIN)

    for example中包括的:
    标记出正负
    剔除空白字符
    判断数值大小是否超过范围
    非法输入

    LeetCode 比较快的算法,很简洁

    class Solution:
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            import re
            
            pattern = r"[\s]*[+-]?[\d]+"
            match = re.match(pattern, str)
            if match:
                res = int(match.group(0))
                if res > 2 ** 31 - 1:
                    res = 2 ** 31 -1
                if res < - 2 ** 31:
                    res = - 2 ** 31
            else:
                res = 0
            return res
    

    自己实现的

    class Solution:
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            if '' == str.strip():
                return 0
            sign, base, i = 1, 0, 0
            INT_MAX = 2147483647
            INT_MIN = -INT_MAX - 1
            while (str[i] == ' '):
                i += 1
            if str[i] == '-' or str[i] == '+':
                if str[i] == '-':
                    sign = -1
                i += 1
    
            while i < len(str) and '0' <= str[i] <= '9':
    #如果`base > MAX_VALUE/10`,那么`base*10 + new_value` > `base*10` > `MAX_VALUE`。这个应该很容易理解,这种情况下就会发生溢出。
    #若`base == INT_MAX/10`,而且`new_value = str.charAt(i++) - '0'`大于`7`,也会发生溢出。因为`MAX_VALUE = 2147483647`
                if base > INT_MAX // 10 or base == INT_MAX // 10 and int(str[i]) > 7:
                    return INT_MAX if sign == 1 else INT_MIN
    
                base = 10 * base + int(str[i])
                i += 1
    
            return base * sign
    

    相关文章

      网友评论

        本文标题:Python字符串转换整数 (atoi)

        本文链接:https://www.haomeiwen.com/subject/rrzocqtx.html