Loading...
Loading...
The electronics lab has an old calculator that takes expressions in postfix form: each operator comes right after the two values it works on. So 2 3 + means 2 + 3, and 2 3 4 * + means 2 + (3 × 4) = 14.
Given a postfix expression, print its value. The operators are +, -, * and /. Division keeps only the whole part and drops the rest toward zero, like Java's / on whole numbers: 7 / 2 is 3 and -7 / 2 is -3.
+, -, *, /.Example 1
Input
5 1 2 + 4 * + 3 -
Output
14
1 + 2 = 3, then 3 × 4 = 12, then 5 + 12 = 17, then 17 - 3 = 14.
Example 2
Input
7 10 - 2 /
Output
-1
7 - 10 = -3, and -3 / 2 drops the .5 toward zero, so the answer is -1.
Try the problem first. Open one hint at a time.
Read the tokens from left to right. A number has to wait until its operator arrives.
Push every number on a stack. When an operator comes, its two values are the top two items.
Pop the second value first, then the first value, work out first operator second, and push the result.
The values can reach 10^18, so use long. At the end, the only item left is the answer.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor