Skip to content
RED SAGSkills
medium30 ptsstackstrings

Evaluate a Flat Expression

Evaluate an arithmetic expression made of non-negative integers, the operators +, -, *, / and spaces. There are no parentheses. * and / bind tighter than + and -, operators of equal precedence go left to right, and division truncates toward zero.

The expression is always valid and never divides by zero. Do not use eval.

Example 1

Input: expr = "3+2*2"
Output: 7

Example 2

Input: expr = " 14 - 3/2 "
Output: 13

Constraints

  • 1 <= expr.length <= 3 * 10^4
  • Every intermediate result fits in a safe integer.
Hint 1

Push signed terms onto a stack; apply * and / immediately to the top of the stack.

Hint 2

Sum the stack at the end. Use Math.trunc for division.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, DevOps Engineer

Run checks your code on 2 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.