Basic Calculator II
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #227
Evaluate an expression string containing non-negative integers, + − * / and spaces (no parentheses). Integer division truncates toward zero. Don't use eval.
Examples
text
"3+2*2" → 7
" 3/2 " → 1
" 3+5 / 2 " → 5Hints
*and/bind tighter than+and−.- Keep a stack of terms: push
+nor−n; for*and/, combine with the top immediately.
Approach
Scan while building the current number. When you hit an operator (or the end), apply the previous operator: + pushes num, − pushes −num, * replaces the top with top·num, / replaces the top with trunc(top/num). Then remember the new operator. The answer is the sum of the stack. O(n).
Complexity
Time: O(n). Space: O(n).
Python solution
def calculate(s):
st, num, op = [], 0, "+"
for i, ch in enumerate(s):
if ch.isdigit():
num = num * 10 + int(ch)
if (not ch.isdigit() and ch != " ") 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)JavaScript solution
function calculate(s) {
const st = []; let num = 0, op = '+';
for (let i = 0; i < s.length; i++) {
const ch = s[i], digit = ch >= '0' && ch <= '9';
if (digit) num = num * 10 + Number(ch);
if ((!digit && ch !== ' ') || i === s.length - 1) {
if (op === '+') st.push(num); else if (op === '-') st.push(-num);
else if (op === '*') st.push(st.pop() * num); else st.push(Math.trunc(st.pop() / num));
op = ch; num = 0;
}
}
return st.reduce((a, b) => a + b, 0);
}