All problems
0540HardMathStringStackRecursion

Till Keypad Expression

Tracked in this browser only
Write code

Trains the technique from

LeetCode 772Basic Calculator III

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A market-stall till lets the trader type a whole price calculation on the keypad before pressing total. The keystrokes arrive as the string s, which contains decimal digits, the four operator keys +, -, * and /, and the bracket keys ( and ). There are no spaces, every operator sits between two operands, and no number is preceded by a sign.

Work out what the till should display, following these rules:

  • * and / bind more tightly than + and -.
  • Operators that bind equally tightly are applied from left to right, so 60/4/5 is 3.
  • A bracketed section is worked out first and then used as a single operand.
  • / is whole-number division that throws away any fractional part, rounding toward zero. So (0-9)/4 is -2, not -3.
  • No division by zero occurs.

Return the displayed value. Do not pass the string to a built-in expression evaluator.

Examples

Example 1

Input
s = "9+40/6*2"
Output
21

The tighter operators go first: 40/6 discards the remainder and gives 6, then 6*2 is 12, and finally 9+12 is 21.

Example 2

Input
s = "(70-90)/6"
Output
-3

The bracket gives -20, and dividing -20 by 6 rounds the quotient toward zero, so the till shows -3.

Example 3

Input
s = "4*(8+2*(9-6))-50/4"
Output
44

The inner bracket is 9-6 = 3, so 2*3 = 6 and the outer bracket is 8+6 = 14. Then 4*14 = 56, and 50/4 = 12, leaving 56-12 = 44.

Constraints

  • 1 <= s.length <= 10^4
  • s contains only the characters '0'-'9', '+', '-', '*', '/', '(' and ')'.
  • s is a well-formed expression in which every operator is binary.
  • The final value and every value reached along the way lie between -2^31 and 2^31 - 1.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def calculate(s: str) -> int:
Java
public int calculate(String s)
September 7
Apply