FastPrepEvaluate Arithmetic with Operator Precedence

Evaluate Arithmetic with Operator Precedence

Roblox logoRoblox● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Evaluate a valid integer expression containing binary +, -, * and /, and return its integer value.

For this exercise, assume input is a nonnegative decimal literal followed by zero or more operator/literal pairs. Multiplication and division have higher precedence than addition and subtraction; operators with equal precedence associate from left to right. Division truncates toward zero. ASCII spaces may occur between tokens, and leading zeroes are decimal. Parentheses, unary signs and invalid-input handling are outside this contract.

For this exercise, assume length at most 500, literals from 0 through 1000000, nonzero divisors, and signed 32-bit arithmetic intermediates/final results.

Function

evaluateWithPrecedence(expression: String) → int

Examples

Example 1

expression = "3+2*2"return = 7

This authored example multiplies first, so the result is 7.

Example 2

expression = "14-7/2"return = 11

This authored example truncates 7/2 to 3 before subtraction, giving 11.

Example 3

expression = "20/3/2"return = 3

This authored example divides from left to right: 20/3 is 6 and 6/2 is 3.

Constraints

  • For this exercise, assume 1 <= expression.length <= 500.
  • Every literal is an integer from 0 through 1000000.
  • Input is always valid under the stated flat four-operator grammar and every divisor is nonzero.
  • All arithmetic intermediates and the final result fit signed 32-bit integers.

More Roblox problems

See Roblox hiring insights
public int evaluateWithPrecedence(String expression) {
    // Write your code here.
    return 0;
}
expression"3+2*2"
expected7
Checking account…