8. String to Integer (atoi) [easy] (Python)

题目链接

https://leetcode.com/problems/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.

题目翻译

实现“atoi”函数,将字符串转换成整数。
提示:请仔细考虑所有可能的输入情况。

思路方法

通过试错可以总结出要注意的四个点:

  1. 输入字符串为空、或其他不合法情况,返回0;
  2. 字符串开头的空格要在预处理中删掉;
  3. 处理可能出现的正负号“+”,“-”,正负号只能出现一次;
  4. 超出整数范围的值取整数范围的边界值。

思路一

按照上面要注意的点,比较可读的解法如下。

代码

class Solution(object):
    def myAtoi(self, str):
        """ :type str: str :rtype: int """
        if not str:
            return 0
        str = str.strip()
        number, flag = 0, 1
        if str[0] == '-':
            str = str[1:]
            flag = -1
        elif str[0] == '+':
            str = str[1:]
        for c in str:
            if c >= '0' and c <= '9':
                number = 10*number + ord(c) - ord('0')
            else:
                break
        number = flag * number
        number = number if number <= 2147483647 else 2147483647
        number = number if number >= -2147483648 else -2147483648
        return number

思路二

用正则表达式来简化上面的过程。

代码

class Solution(object):
    def myAtoi(self, str):
        """ :type str: str :rtype: int """
        str = str.strip()
        try:
            res = re.search('(^[\+\-]?\d+)', str).group()
            res = int(res)
            res = res if res <= 2147483647 else 2147483647
            res = res if res >= -2147483648 else -2147483648
        except:
            res = 0
        return res

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52053932

    原文作者:coder_orz
    原文地址: https://blog.csdn.net/coder_orz/article/details/52053932
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞