Basic Calculator
Real-world version: Bracketed Offset TotalThe statement here is our own: the same inputs, outputs and technique.
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-7or-(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.
def evaluate_offsets(expr: str) -> int:public int evaluateOffsets(String expr)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's