【leetcode❤python】 8. String to Integer (atoi)

#-*- coding: UTF-8 -*-
#需要考虑多种情况
#以下几种是可以返回的数值
#1、以0开头的字符串,如01201215
#2、以正负号开头的字符串,如‘+121215’;‘-1215489’
#3、1和2和空格混合形式【顺序只能是正负号-0,空格位置可以随意】的:‘+00121515’
#4、正数小于2147483647,负数大于-2147483648的数字
#其他的情况都是返回0,因此在判断 是把上述可能出现的情况列出来,其他的返回0
#AC源码如下
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if str=="":return 0
        strl=[]
        count=0
        flag=0
        str=str.strip()
        for  c in str:
            if c>='1' and c<='9':
                count+=1
                strl.append(c)
            elif c=='0' and count!=0:
                count+=1
                strl.append(c)
            elif c=='-' and flag==0:
                flag+=1
                strl.append(c)
            elif c=='+' and flag==0:
                flag+=1
                strl.append(c)
            elif c=='0':continue
            else:break
        str=''.join(strl)
        if str=="":return 0
       
        if str[0]!='-'and str[0]!='+'  :return int(str) if int(str)<2147483647 else 2147483647
        elif str[0]=='-' and len(str)>1 :return -int(str[1:]) if int(str[1:])<2147483648 else -2147483648
        elif str[0]=='+' and len(str)>1 :return  int(str[1:]) if int(str[1:])<2147483647 else 2147483647
        return 0
            
sol=Solution()
print sol.myAtoi("-2147483648")



转载于:https://www.cnblogs.com/kwangeline/p/6059511.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值