Last Updated: November 19, 2025
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Input: s = "3+2*2"
Output: 7
Input: s = " 3/2 "
Output: 1
Input: s = " 3+5 / 2 "
Output: 5
s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.s represents a valid expression.The problem requires us to evaluate a string containing a mathematical expression with +, -, *, and /. A straightforward approach is to use two stacks: one for numbers and another for operators. This is similar to the standard method used for evaluating expressions.
* and / have higher precedence).By recognizing the fact that * and / operations are executed immediately and have higher precedence, we can simplify our approach by using only one stack. We can optimize by directly evaluating the immediate * and / results on the numbers residing in the stack.
* and / into the stack.We can make this more efficient by minimizing stack use to only necessary intermediate results. We can modify the processed result in place using a single pass through the string. By evaluating high-priority operations as soon as possible, only results of addition/subtraction need to be stored.
*, /) immediately and push intermediate results into the stack.