FastPrepEvaluate Parenthesized Addition and Subtraction

Evaluate Parenthesized Addition and Subtraction

Atlassian logoAtlassian● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Evaluate a valid integer expression containing additions, subtractions and parenthesized groups, and return its integer value.

For this exercise, assume an expression is a factor followed by zero or more binary +/- operators and factors. A factor is a nonnegative decimal literal or a parenthesized expression, optionally preceded by one unary minus. ASCII spaces may occur between tokens; leading zeroes are decimal. Input is valid and nonempty. Multiplication, division, unary plus and invalid-input handling are outside this contract.

For this exercise, assume length at most 500, nesting depth at most 50, literals 0 through 1000000 and signed 32-bit intermediate/final values.

Function

evaluateParenthesized(expression: String) → int

Examples

Example 1

expression = "8-(3-2)"return = 7

This authored example subtracts the entire grouped result and evaluates to 7.

Example 2

expression = "-(2+3)+10"return = 5

This authored example applies unary minus to a group and evaluates to 5.

Example 3

expression = "1-(-2)+4"return = 7

This authored example subtracts a negative factor and evaluates to 7.

Constraints

  • For this exercise, assume 1 <= expression.length <=500 and nesting depth at most 50.
  • Every literal is from 0 through 1000000 and all intermediate/final results fit signed 32-bit integers.
  • Only the declared valid decimal/plus/minus/parenthesis/unary-minus grammar is admitted.

More Atlassian problems

See Atlassian hiring insights
public int evaluateParenthesized(String expression) {
    // Write your code here.
    return 0;
}
expression"8-(3-2)"
expected7
Checking account…