【LeetCode】8. String to Integer (atoi)解题报告(Python)

测试代码:

class Solution:
    def myAtoi(self, str):
        str = str.lstrip()
        if str == '':
            return 0
        flag = None
        if str[0] == '+':
            flag = 1
            str = str[1:]
        elif str[0] == '-':
            flag = 0
            str = str[1:]
        list = []
        for c in str:
            try:
                if int(c) != 0 or list != []:
                    list.append(c)
                if len(list) > 10:
                    break
            except:
                break
        if list == []:
            return 0
        num = int(''.join(list))
        num = (0 - num) if flag == 0 else num
        return min(max(-2147483648, num), 2147483647)

print(Solution().myAtoi(' -0000000000102345678 w'))    #提交时请删除该行

解题思路:

这道题目的目的是将字符串转换为数字,可以多提交几次用作检查,注意细节问题不大。

代码说明:

1、用lstrip方法去除字符串左端空格(类似方法:rstrip-去右端,strip-去两端),如果字符串为空直接返回0,再用flag做标志位记录去除空格后首字符是否为'+','-'号,若有则记录并从第二位截取字符串。

2、代码中的16、17行可以改写成如下方式,即当list为空同时c为0则可跳过该数字(结束本次循环)。

                if int(c) == 0 and list == []:
                    continue
                list.append(c)

3、对格式化后的字符串遍历,try:   if int(c) != 0 or list != []:   list.append(c),这里首先保证c可以转换为数字,然后c不为0或者list不为空则将c加入list。if len(list) > 10:   break,因为2^31为10位,所以数字不能超过10位,同时不能转换为数字也break。

4、如果list为空则返回0,int(''.join((list)))表示把list的数组合起来转换为int,再加上符号位,最后判断数值区间再返回。

附:从网上看的正则代码,经过一点修改看起来非常简洁

class Solution(object):
    def myAtoi(self, str):
        str = str.strip()
        try:
            res = int(re.search('(^[\+\-]?\d+)', str).group())
        except:
            res = 0
        return min(max(-2147483648, res), 2147483647)

猜你喜欢

转载自blog.csdn.net/L141210113/article/details/87898532