Loading...
Loading...
The hostel mess wants a small calculator for its bills. A clerk types an expression the normal way, such as 2 + 3 * ( 10 - 4 ), and the calculator must print its value.
Use the usual rules. Brackets are worked out first. Then * and / come before + and -. Operators of the same level go from left to right, so 10 - 4 - 3 is 3. 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.
+, -, *, /, or a bracket ( or ).Example 1
Input
2 + 3 * ( 10 - 4 )
Output
20
The bracket gives 6, then 3 × 6 = 18, then 2 + 18 = 20.
Example 2
Input
10 - 4 - 3
Output
3
Same level, left to right: (10 - 4) - 3 = 3.
Try the problem first. Open one hint at a time.
Use two stacks: one for numbers and one for operators and opening brackets.
Before you push a new operator, first work out every operator on the stack that has the same or a higher level, until you meet a (.
To work out one operator, pop it and the top two numbers. The top number is the right-hand value. Push the result.
For ), work out operators until the ( and then remove the (. At the end, work out everything left. Use long for the values.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor