Evaluate an Arithmetic Expression Written in Words
Updated
Problem statement
An arithmetic expression is written with words instead of symbols, for example "5 plus 4 times negative 5". Evaluate expression and return its value.
The expression is a list of tokens separated by single spaces:
- A number is a non-negative integer written in digits, such as
0or42. - The word
negativecan appear right before a number. It makes that one number negative. - The word
plusmeans addition and the wordtimesmeans multiplication.
Multiplication comes before addition, as in ordinary math. First multiply each run of numbers joined by times into one term, then add all the terms. The expression has no parentheses and is always valid.
Function
evaluateExpression(expression: String) → longExamples
Example 1
expression = "5 plus 4 times negative 5"return = -15timesgoes first:4 times negative 5is4 × (-5) = -20.- Then add:
5 + (-20) = -15.
Example 2
expression = "negative 3 times 2 times negative 4 plus 10"return = 34- The first term multiplies three numbers:
(-3) × 2 × (-4) = 24. - Then add the second term:
24 + 10 = 34.
Example 3
expression = "12 times 0 plus negative 8"return = -812 × 0 = 0.- Then
0 + (-8) = -8.
Constraints
1 <= expression.length <= 10^4expressionis made of tokens separated by single spaces, with no space at the start or the end.- An operand is a number, or the word
negative, a space and a number. The expression starts and ends with an operand, and operands and the operatorsplusandtimestake turns. - Every number is an integer from
0to10^4written in digits with no leading zeros. - While you evaluate as described, every partial product, every term, and every running total of the terms from the left has an absolute value of at most
10^15.
More Brex Phone Screen questions
Similar questions at other companies
- Evaluate a Flat Expression or Report Invalid InputMeta · PHONE SCREENMeta interview questions
- Strict Text to Integer for a Given SizeAdobe · PHONE SCREENAdobe interview questions
- Evaluate an Arithmetic ExpressionAkuna Capital · PHONE SCREENAkuna Capital interview questions
- Solve a Linear Equation in xNutanix · PHONE SCREENNutanix interview questions
- Stack Formula InterpreterTypeSafe AI · PHONE SCREEN
- Transaction Fee Calculator — Parts 1–2: Basic Fee Calculation and Conditional Fee RulesStripe · PHONE SCREENStripe interview questions
- Parse, Normalize, and Combine PolynomialsSquarepoint Capital · PHONE SCREENSquarepoint Capital interview questions
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Simplify a Quadratic ExpressionOpenAI · OAOpenAI interview questions
- Balance a Chemical EquationMicrosoft · OAMicrosoft interview questions