题解 | #把字符串转换成整数(atoi)#

把字符串转换成整数(atoi)

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return int整型
#
class Solution:
    def StrToInt(self , s: str) -> int:
        # write code here
        s = s.strip()
        if len(s)==0:
            return 0
        if s[0]=="+":
            Flag=1
            s=s[1:]
        elif s[0]=="-":
            Flag=0
            s=s[1:]
        elif s[0].isdigit():
            Flag=1
        else:
            Flag=0
            return 0
        
        L=[]
        if len(s)==0:
            return 0
        for i in s:
            if i.isdigit():
                L.append(i)
            else:
                break
        #print(L)
        if len(L) ==0:
            return 0

        x="".join(L)
        #print(x)
        #print(type(x))
        x=int(x)
        if Flag:
            if x <=2 ** 31 -1:
                return x
            else:
                return  2 ** 31 -1
        else:
            if x <= 2 ** 31:
                return -x
            else:
                return -2 ** 31

全部评论

相关推荐

28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务