String to Integer (atoi)解题报告

感觉string的题目在leetcde中都比较靠前,是不是因为是最早出的,所以题目的表述都有一些简略,很多时候看不懂题orz。

题目描述

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.

解题思路

这道题就是要考虑一些特殊的情况:

1 去除空格

2 数字前出现多余的字符

3 数字中有空格或非数字字符

4 越界

代码

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if len(str)==0:
            return 0
        str=str.strip()
        isP=False
        isN=False
        has=False
        for i in range(len(str)):
            if str[i]=='+':
                isP=True
                has=True
            if str[i]=='-':
                isN=True
                has=True
        if has:
            if isP and isN:
                return 0
        if has:
            str=str[1:]
        i=0
        while i<len(str) and ord(str[i]) in range(48,58):
            i+=1
        r=0
        if i>0:
            r=int(str[:i])
        if isN:
            r*=-1
        return max(min(r,pow(2,31)-1),-pow(2,31))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值