Given a string s representing a valid expression with integers, +, -, (, ), and spaces, implement a basic calculator to evaluate it and return the result. No * or / operators.
s = "1 + 1"2s = " 2-1 + 2 "3s = "(1+(4+5+2)-3)+(6+8)"23s = "2-(5-6)"3num = num*10 + digitresult += sign*num, reset num=0, update signresult and sign onto stack, then reset result=0, sign=+1num, then pop: result = savedSign × result + savedResultresult + sign*num (handles trailing number after last operator)
Parentheses create nested scopes — each ( starts a fresh sub-expression with its own running sum and sign context.
The stack is our memory: we save the outer result and the sign that precedes the '('
(which determines how the inner result merges back).
When ) closes the scope, we do inner × savedSign + savedResult, perfectly restoring context.
Stack depth equals nesting depth — O(n) space in the worst case.
Converting to postfix first works, but it is more machinery than needed. With only plus and minus, a running result and a sign are enough, plus a stack for brackets.
Keep a running result and the sign of the next number. On an opening bracket, push the current result and sign, and start a fresh result inside. On a closing bracket, finish the inner result, then pop: the outer result plus the sign times the inner result.
With only plus and minus, keep a result and a sign. Brackets save and restore that state with a stack.
Run the animation above on your own input, or watch the 1:31 video explanation of Basic Calculator with a dry run and Java code.