leetcode--8. String to Integer (atoi)

题目:8. String to Integer (atoi)

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

将给定的字符串转为整数。需要考虑一些特殊的输入情况,比如前导空格要忽略正负号不忽略,要转换到最开始的非数字字符等。具体有哪些坑在题目下面列出了一部分,其他的瞎改通过了。

python:

class Solution(object):
    def myAtoi(self, string):
        """
        :type str: str
        :rtype: int
        """
        if not string:
            return 0
        s = ""
        start = 0
        while string[start] == ' ':
            start += 1
        s = string[start:len(string)]
        start = end = 0
        if len(s) == 1:
            if s[0] < '0' or s[0] > '9':
                return 0
            else:
                return int(s)
        if (s[0]<'0' or s[0]>'9') and s[0]!='+' and s[0]!='-':
            return 0
        if (s[1] < '0' or s[1] > '9'):
            if (s[0]>='0' and s[0]<='9'):
                return int(s[0])
            else:
                return 0 
        while s[start] < '0' or s[start] > '9':
            start += 1
            if start >= len(s):
                return 0
        end = start
        while s[end] >= '0' and s[end] <= '9':
            end += 1
            if end >= len(s):
                break
        res = 0
        if s[0] == '-':
            res = -int(s[start:end])
        else:
            res = int(s[start:end])
        # res=int(s[start:end]) if s[0]=='+' else -int(s[start:end])
        if res >= -0x80000000 and res <= 0x7fffffff:
            return res
        else:
            return 0x7fffffff if res > 0 else -0x80000000


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值