227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

You may assume that the given expression is always valid.
Do not use the eval built-in library function.
class Solution:
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        op = '+'
        n = 0
        l = []
        for i in range(len(s)):
            if s[i].isdigit():
                n = n *10 +int(s[i])
            if not s[i].isdigit() and not s[i].isspace() or i == len(s)-1:
                if op == '+':
                    l.append(n)
                if op == '-':
                    l.append(-n)
                if op == '*':
                    a = l.pop()*n
                    l.append(a)
                if op == '/':
                    a = int(l.pop()/n)
                    l.append(a)
                op = s[i]
                n = 0
        num = 0
        while len(l):
            num += l.pop()
        return num
原文地址:https://www.cnblogs.com/bernieloveslife/p/9733363.html