剑指Offer49:把字符串转换成整数

思路:

先判断字符串的第一个字符,看是否是正负号,若是则继续,若不是则返回0

再者判断之后的字符是否都是数字,若是则继续计算反之返回0

最后在考虑正负号。

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if len(s)==0:
            return 0
        else:
            if s[0]>'9' or s[0]<'0':
                if s[0]=='+' or s[0]=='-':
                    a=0
                else:
                    return 0
            else:
                a=int(s[0])*10**(len(s)-1)
            for i in range(1,len(s)):
                if s[i]>='0' and s[i]<='9':
                    a=a+int(s[i])*10**(len(s)-1-i)
                else:
                    return 0
        if s[0]=='+':
            return a
        if s[0]=='-':
            return -a
        return a

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/86075461