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.