美文网首页
227. Basic Calculator II

227. Basic Calculator II

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-11 07:53 被阅读0次
    use stack 
    
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            stack=[]
            num=0
            sign='+'
            for i in xrange(len(s)):
                if s[i].isdigit():
                    num=num*10+int(s[i])
                if (s[i]!=' ' and not s[i].isdigit()) or i==(len(s)-1):
                    if sign=='+':stack.append(num)
                    elif sign=='-':stack.append(-num)
                    elif sign=='*':
                        stack.append(stack.pop()*num)
                    elif sign=='/':
                        last_num=stack.pop()
                        if last_num/num<0 and last_num%num!=0:
                            temp=last_num/num+1
                        else:
                            temp=last_num/num
                        stack.append(temp)
                    sign=s[i]
                    num=0
                        
            return sum(stack)
    
    use regular expression 
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            tokens=iter(re.findall(r'\d+|\S',s))
            total=0
            sign=1
            for token in tokens:
                if token in '+-':
                    total+=sign*cache
                    sign=' +'.find(token)
                elif token in '*/':
                    n=int(next(tokens))
                    cache=cache*n if token=='*' else cache/n
                else:
                    cache=int(token)
            return total+sign*cache 
                
    

    相关文章

      网友评论

          本文标题:227. Basic Calculator II

          本文链接:https://www.haomeiwen.com/subject/jvtumttx.html