Leetcode8_String to Integer (atoi)

8. 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.

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.“`

python代码

我的解题代码:
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """

        # !!!!最开始没有想到这种情况
        if str == '':
            return 0
        # 控制正负
        positive = 1
        lenstr = len(str)
        # 需要初始化sum和k
        sum = 0
        k = 0

        # 如果为空格就舍去,直到出现有字符的一项
        for i in range(lenstr):
            if str[i] != ' ':
                k = i
                break
        str = str[k:]

        # 判断如果第一个符号是+或-,则从第二个字符开始取数字部分
        if str[0] == '-':
            positive = -1;
            str = str[1:]
        elif str[0] == '+':
            str = str[1:]
        #print (str)
        for i in str:
            # ord函数将字符转化成ascii的值,比如ord('0')=48
            if (ord(i) >= ord('0') ) and (ord(i) <= ord('9')):
                sum = sum * 10 + (ord(i) - ord('0'))
                #提交时没有考虑到下面的情况
                if positive ==1 and sum >= 2147483647:
                    return 2147483647
                if positive == -1 and sum >= 2147483648:
                    return -2147483648
            else:
                break
        sum *= positive
        return sum

# f = Solution()
# str = '             -012a3'
# print(f.myAtoi(str))
参考答案:
class Solution:
    # @return an integer
    def atoi(self, str):
        str = str.strip()
        #原答案str = re.findall('(^[\+\-0]*\d+)\D*', str)
        #简化,还需要学习正则化
        str = re.findall('^[+\-]?\d+', str)
        try:
            #这一步int就好使。白费我各种x10
            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
解析:
  • strip()函数
    • s.strip(rm) 删除s字符串开头、结尾处,位于rm删除序列的字符
    • s.lstrip(rm) 删除s字符串开头处,位于 rm删除序列的字符
    • s.rstrip(rm) 删除s字符串结尾处,位于 rm删除序列的字符
>>>str = '      - a0 bb   '
>>>strstrip = str.strip()
>>>strstrip
`>>>'- a0 bb'`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值