Show problems as
Classic problem #224HardMathStringStackRecursion

Basic Calculator

Real-world version: Bracketed Offset Total
Tracked in this browser only
Read Basic Calculator on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstExpression Evaluation · Stacks & Queues, animated step by step

A surveyor's notebook records how much a benchmark has moved as one long offset line, for example 40-(6+9). The line is a string expr built only from digits, +, -, round brackets and spaces.

Reading rules for the line:

  • + and - between two pieces add and subtract, applied left to right.
  • A bracketed group is read on its own, and whatever sits in front of the group applies to its whole value.
  • - may also appear as a sign in front of a single number or a bracketed group, as in -7 or -(4+2). + is never used that way.
  • Spaces carry no meaning.

Return the total offset the line describes. Passing the line to a language-provided expression evaluator is not allowed.

Examples

Example 1

Input
expr = "7 - (2 + 9)"
Output
-4

The bracketed group is worth 11, and the minus in front of it applies to all of it, so the line reads 7 - 11.

Example 2

Input
expr = "-(6-11)+4"
Output
9

The group is worth -5, the leading sign flips it to 5, and the trailing 4 brings the total to 9.

Example 3

Input
expr = "((3+12)-(5-1))-8"
Output
3

The inner groups are 15 and 4, so the outer group is 11, and subtracting 8 leaves 3.

Constraints

  • 1 <= expr.length <= 3 * 10^5
  • expr holds only digits, '+', '-', '(', ')' and ' '
  • expr is always a well-formed offset line
  • '+' never appears as a sign in front of a number or a group
  • '-' may appear as a sign in front of a number or a group
  • Two operators never sit next to each other
  • Every number and every running total fits in a signed 32-bit integer

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def evaluate_offsets(expr: str) -> int:
Java
public int evaluateOffsets(String expr)