Evaluation of Postfix Expression
You're given an arithmetic expression exp written in postfix form. Evaluate it and return the final result, supporting the operators +, -, *, and /. Operands are single digits (0 through 9) and the expression has no separators. Division truncates toward zero. The expression is valid and never divides by zero.
Input Format
Implement evaluatePostfix(exp). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
exp = "231*+9-" Output
-4 Example 2
Input
exp = "82/" Output
4 Constraints
- 1 <= length of expression <= 100
Test Cases (2)
Case 1
Args: ["231*+9-"]
Expected: -4
Case 2
Args: ["82/"]
Expected: 4
Topics
Stack-Based Evaluation
This version uses single-digit operands with no separators. Pop the right operand before the left; division truncates toward zero.
function evaluatePostfix(exp) {
const stack = [];
for (const c of exp) {
if ('+-*/'.includes(c)) {
const b = stack.pop(), a = stack.pop();
if (c === '+') stack.push(a + b);
else if (c === '-') stack.push(a - b);
else if (c === '*') stack.push(a * b);
else stack.push(Math.trunc(a / b));
} else stack.push(Number(c));
}
return stack[0];
}Time: O(n) | Space: O(n)
Saved in this browser only. Private to you.