FastPrepEvaluate Addition and Multiplication

Evaluate Addition and Multiplication

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Evaluate a valid arithmetic expression containing nonnegative decimal integers, binary addition +, multiplication x, and optional ASCII spaces around tokens.

Multiplication has higher precedence than addition. Leading zeros are allowed and do not change a decimal integer’s value. Spaces never split the digits of one number. Return the integer result.

The grammar contains no subtraction, division, unary signs or parentheses. There is at least one number, and each binary operator has a number on both sides.

Function

evaluateExpression(expression: String) → int

Examples

Example 1

expression = "2+3x4"return = 14

Multiplication is evaluated first in this practice grammar: 3x4 is 12, then 2+12 is 14.

Example 2

expression = "10x2+3x4"return = 32

The two products are 20 and 12; adding them gives 32.

Example 3

expression = "7"return = 7

A single literal evaluates to its own value.

Constraints

  • 1 <= expression.length <= 10^4.
  • The expression contains only decimal digits, spaces, + and lowercase x and follows the stated valid grammar.
  • Every literal, intermediate product, intermediate sum and final result is between 0 and 2147483647.

More Meta problems

See Meta hiring insights
public int evaluateExpression(String expression) {
    // Write your solution here.
}
expression"2+3x4"
expected14
Checking account…