[LeetCode] String to Integer (atoi) Python

Leetcode上的一道中等难度的题,题目限制非常多。

原题链接:https://leetcode.com/problems/string-to-integer-atoi/#/description 


题目要求:Implement atoi to convert a string to an integer (把输入的字符串转换为整数)

题目限制:

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.

1. 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,如果没有,则返回0.

2. 当异常字符(非0-9之间的数)出现时,从异常字符开始截断后面所有字符,只转换异常字符之前的字符为整数,但要注意+、-可以作为整形数开头;

3.还需要考虑边界问题,如果超过了整形数的范围[-2147483648,2147483647],则用边界值替代当前值。


这题就是坑比较多,诸多情况不能一下子完全考虑到,比如"      +10"可以转换。但“+   10”就不能转换,“123a456”就只能转换“123”了,限制情况都明了,自然好解,先来一个我自己的方法,把所有情况考虑进去,

Python 解法一(直接法,58ms):

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()           #去除字符串前面空格
        len_str = len(str)
        int_set = ['0','1','2','3','4','5','6','7','8','9']
        atoi = '0'
        atoi_max = 2147483647
        atoi_min = -2147483648
        if len_str > 0:
            i = 0
            if str[0] in ["+","-"]:     #判断字符串带"+" or "-"号
                i = 1
                atoi = str[0] + atoi
            for j in range(i,len_str):
                if str[j] in int_set:
                    atoi = atoi + str[j]
                else:
                    break
        atoi = int(atoi)
        if atoi > atoi_max:             #判断溢出
            atoi = atoi_max
        if atoi < atoi_min:
            atoi = atoi_min
        return atoi


Leetcode上有个哥们用的正则,也是超赞的,正则^[+\-]表示匹配开头是+或-号,?代表匹配0或1次,\d代表匹配0-9的整数,+代表1或多个。值得一提的是正则中取反,是用[^ 排除内容],如:[^ \d]排除数字。
Python 解法二(正则):

class Solution:
    # @return an integer
    def atoi(self, str):
        str = str.strip()
        str = re.findall('^[+\-]?\d+', str)

        try:
            result = int(''.join(str))
            MAX_INT = 2147483647
            MIN_INT = -2147483648
            if result > MAX_INT > 0:
                return MAX_INT
            elif result < MIN_INT < 0:
                return MIN_INT
            else:
                return result
        except:
            return 0
 欢迎讨论

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值