#-*- 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")



相关文章:

  • 2021-11-05
  • 2021-08-05
  • 2021-12-16
  • 2021-06-23
  • 2021-10-24
  • 2022-01-10
  • 2021-09-01
猜你喜欢
  • 2021-11-17
  • 2021-07-21
  • 2021-06-29
  • 2022-01-27
  • 2022-03-05
  • 2022-02-04
  • 2021-10-30
相关资源
相似解决方案