Evaluate a Postfix Expression
Problem
A postfix expression has numbers and the operators + - * / separated by spaces; the operator comes after its two numbers (3 4 + means 3 + 4). Print the value. Division cuts the result toward zero. The input is always valid and never divides by zero.
Constraints
- 1 <= tokens <= 10^4
- |intermediate values| <= 10^9
Examples
Input
5 1 2 + 4 * + 3 -
Output
14
Solutions
Postfix needs no brackets and no priority rules; one left-to-right pass with a stack is enough. Java and JavaScript cut division toward zero; Python's // rounds down, so we divide the absolute values and fix the sign.
/*
* Problem : Postfix value.
* Input : One line of tokens.
* Output : The value.
* Approach: Use a stack.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(String s) {
// Step 1: A stack holds the numbers that wait for an operator.
java.util.ArrayDeque<Long> stack = new java.util.ArrayDeque<>();
for (String token : s.trim().split("\\s+")) {
if (token.length() == 1 && "+-*/".contains(token)) {
// Step 2: An operator takes the two top numbers. The second number from the top is the left side.
long right = stack.pop();
long left = stack.pop();
if (token.equals("+")) {
stack.push(left + right);
} else if (token.equals("-")) {
stack.push(left - right);
} else if (token.equals("*")) {
stack.push(left * right);
} else {
stack.push(left / right);
}
} else {
stack.push(Long.parseLong(token));
}
}
// Step 3: At the end, one number is left. It is the answer.
return stack.pop();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Why is the right operand popped first?