python写算法题:leetcode: 8. String to Integer (atoi)

来源:互联网 发布:2017经济下行 知乎 编辑:程序博客网 时间:2024/06/14 21:01

https://leetcode.com/problems/string-to-integer-atoi/#/description

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """                realstr = ""        negative = 1        stage = 0                for s in str:            if stage==0:                if s in " \t":                     continue                if s == '+':                    stage=1                    continue                if s == '-':                    stage=1                    negative=-1                    continue                if s >= '0' and s<= '9':                     realstr+=s                    stage=2                    continue                break            if stage!=0:                if s >= '0' and s<= '9':                     realstr+=s                else:                     break                    if realstr=="": return 0        res=0        for s in realstr:            res=ord(s)-ord('0')+res*10        res=negative*res        if(res>2147483647) : return 2147483647        if(res<-2147483648) : return -2147483648        return res


阅读全文
0 0