SDE & MLE Prep

227. Basic Calculator II

Problem

Evaluate the expression s containing non-negative integers, + - * / and spaces (no parentheses), with the usual precedence. Division truncates toward zero.

Example: "3+2*2" → 7; " 3/2 " → 1

No parentheses, but * / bind tighter. When an operator (or the end) is reached, apply the previous operator: +x / -x push, * / / combine with the top. Sum the stack.

Complexity: O(n).

class Solution:
    def calculate(self, s: str) -> int:
        st, num, op = [], 0, "+"
        for i, ch in enumerate(s):
            if ch.isdigit():
                num = num * 10 + int(ch)
            if ch in "+-*/" or i == len(s) - 1:
                if op == "+": st.append(num)
                elif op == "-": st.append(-num)
                elif op == "*": st.append(st.pop() * num)
                else: st.append(int(st.pop() / num))
                op, num = ch, 0
        return sum(st)