dsa · hard

Control-Room Arithmetic

A control panel prints expr, an arithmetic expression containing non-negative integers, the operators + and -, parentheses, and spaces. Evaluate it with the usual precedence (parentheses first, then left-to-right) and return the integer result. A - directly before a number or an opening parenthesis negates that operand.

Arguments

The expression is always valid.

Example

expr = "1 + (2 - 3)" → parentheses first: 2 - 3 = -1, then 1 + (-1) → 0.

expr = " 2-1 + 2 " → left to right: 2 - 1 + 2 → 3.

Constraints

0 <= expr.length <= 3 * 10^5 expr consists of digits, +, -, (, ), and spaces expr represents a valid expression the result fits in a 32-bit signed integer Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
"1 + (2 - 3)"

Expected:
0

Example 2

Input:
" 2-1 + 2 "

Expected:
3

Example 3

Input:
"-(2 + 3)"

Expected:
-5

Open in the Dojo editor