227. Basic Calculator II

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)