Problem Statement

Basic Calculator II

You are given a string like "3+2*2" and you have to figure out what it equals. The string can have digits, the signs '+', '-', '*', '/', and some spaces. Division throws away the fraction part and rounds toward zero, so 7 divided by 2 is 3, not 3.5. There are no parentheses here. The tricky part is order of operations: '*' and '/' have to happen before '+' and '-'. In "3+2*2" you do 2*2 first to get 4, then add 3, which gives 7. The tool that fits this is a stack. A stack is like a pile of plates: you add a plate to the top and you take a plate from the top. The last one you put on is the first one you take off. It fits here because we want to hold the '+' and '-' numbers off to the side until the very end, and the most recent number is the one we may need to grab back when a '*' or '/' shows up. We hold off on the plus and minus numbers, do the times and divide right away, and add up the pile at the end.

mediumStackMathStackTime: O(n) · Space: O(n)

Signals to notice

evaluate +, -, ×, ÷ without parenthesesoperator precedencestack for deferred addition

Brute force first

Not applicable — parsing requires precedence handling.

The key insight

Stack: for + and -, push number (with sign). For × and ÷, pop top, compute, push result. Sum stack at end. O(n).

Trace it on s = " 3+5 / 2 "

init: stack=[], num=0, prev_op='+'
ch='3' -> num=3; ch='+' (op): apply prev '+' -> push 3; stack=[3], prev_op='+', num=0
ch='5' -> num=5; ch='/' (op): apply prev '+' -> push 5; stack=[3,5], prev_op='/', num=0
ch='2' -> num=2; this is last char: apply prev '/' -> pop 5, int(5/2)=2, push 2; stack=[3,2]
loop ends; prev_op='/', num=0 (spaces ignored throughout)
return sum(stack) = 3+2 = 5

What must stay true

× and ÷ resolve immediately (high precedence). + and - are deferred (pushed). Final sum = the answer.

Shape of the loop

stack=[]; num=0; prevOp='+'
for each char ch (with index i):
    if ch is digit: num = num*10 + digit(ch)
    if ch in "+-*/" or i is last:
        '+' -> push num;  '-' -> push -num
        '*' -> push stack.pop()*num;  '/' -> push trunc(stack.pop()/num)
        prevOp = ch; num = 0
return sum(stack)

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Integer division toward zero — use Math.trunc(), not Math.floor().

Stack Pattern