FastPrepBasic Calculator with Multiplication and Parentheses

Basic Calculator with Multiplication and Parentheses

Bloomberg LP logoBloomberg LP● HardNEW GRADPHONE SCREEN
Learn

Problem statement

Evaluate a valid arithmetic expression containing nonnegative decimal integers, binary +, -, and *, parentheses, and optional spaces.

Multiplication has higher precedence than addition and subtraction. Parentheses override precedence. Return the integer result.

Function

calculate(expression: String) → int

Examples

Example 1

expression = "2*(3+4)-5"return = 9

The parenthesized sum is seven, multiplication gives fourteen, and subtracting five gives nine.

Example 2

expression = "12 + 3 * (4 - 2)"return = 18

The multiplication contributes six before the outer addition.

Constraints

  • 1 <= expression.length <= 10^5.
  • The expression is valid and contains only digits, spaces, +, -, *, (, and ).
  • Every operator is binary; unary signs are absent.
  • All intermediate values fit in a signed 32-bit integer.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int calculate(String expression) {
    // Write your code here.
}
expression"2*(3+4)-5"
expected9
Checking account…