Basic Calculator II

 

227. Basic Calculator II

Solution

Reference

  1. Use a stack to store the procedure, only nums are contained inside the stack, so that we can sum all in the end.

  2. ’+’ and ‘-‘ will result in positive and negative numbers.

  3. ‘*’ and ‘/’ requires the calculation with the previous number.

def calculate(self, s):
    if not s:
        return "0"
    stack, num, sign = [], 0, "+"
    for i in xrange(len(s)):
        if s[i].isdigit():
            num = num*10+ord(s[i])-ord("0")
        if (not s[i].isdigit() and not s[i].isspace()) or i == len(s)-1:
            if sign == "-":
                stack.append(-num)
            elif sign == "+":
                stack.append(num)
            elif sign == "*":
                stack.append(stack.pop()*num)
            else:
                stack.append(int(stack.pop()/num))
            sign = s[i]
            num = 0
    return sum(stack)