
Problem
Solution
Submissions
Reverse Polish Notation
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN). Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero.
Example 1
- Input: tokens = ["2", "1", "+", "3", "*"]
- Output: 9
- Explanation: Process "2", "1", "+" → 2 + 1 = 3, then "3", "3", "*" → 3 * 3 = 9
Example 2
- Input: tokens = ["4", "13", "5", "/", "+"]
- Output: 6
- Explanation: Process "13", "5", "/" → 13 / 5 = 2 (truncated), then "4", "2", "+" → 4 + 2 = 6
Constraints
- 1 ≤ tokens.length ≤ 10^4
- tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]
- The given RPN expression is always valid
- The answer and all the intermediate calculations can be represented in a 32-bit integer
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a stack data structure to store operands
- Iterate through each token in the expression
- If the token is a number, push it onto the stack
- If the token is an operator, pop two operands from the stack
- Apply the operator to the two operands and push the result back onto the stack
- The final result will be the only element left in the stack