763. Evaluate an expression with plus and times, no parentheses
Calculators, config languages and even reward checkers for math answers need a small parser. Start with the simplest grammar that still has operator precedence.
Write evaluate(expr) for a string of non-negative integers joined by '+' and '*', with any number of spaces. Multiplication binds tighter than addition. Return the integer result.
def evaluate(expr)Example 1
Input: evaluate('2 + 3 * 4')
Output: 14
Example 2
Input: expr = ' 42 '
Output: 42
Example 3
Input: expr = '2*3*4+1'
Output: 25
Constraints
- Input is always valid.
- No parentheses or minus signs.
Hint 1
Strip all spaces first.
Hint 2
Split on the lower precedence operator.
Hint 3
Start each product at 1 and the sum at 0.
Common mistakes
- Evaluating left to right and getting 20 for '2 + 3 * 4'.
- Starting the product at 0.
Understand the idea
Operator precedence means some operators group first. With only + and *, the expression is a sum of products: 2 + 3 * 4 is 2 + (3 * 4) = 14, not (2 + 3) * 4 = 20. So you can split on the weaker operator, evaluate each piece with the stronger operator, and combine. This split by precedence level is the seed of recursive descent parsing, where each precedence level becomes one function. The same idea shows up when you tokenize and check model answers to arithmetic questions.