Leetcode 150. Evaluate Reverse Polish Notation
You need 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. The given RPN expression is always valid, i.e., it will always evaluate to a result, and there won’t be any division by zero operation.
["2","1","+","3","*"]
Output: 9["4","13","5","/","+"]
Output: 6["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22#include <iostream>
#include <stack>
#include <vector>
#include <string>
class Solution {
public:
int evalRPN(std::vector<std::string>& tokens) {
std::stack<int> s;
for (const auto &token : tokens) {
// if the token is an operator, pop two operands and calculate the result
if (token == "+" || token == "-" || token == "*" || token == "/") {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
if (token == "+") s.push(a + b);
else if (token == "-") s.push(a - b);
else if (token == "*") s.push(a * b);
else if (token == "/") s.push(a / b); // using integer division
} else {
// if the token is an operand, push it onto the stack
s.push(std::stoi(token));
}
}
// the result of the RPN expression will be the last remaining element in the stack
return s.top();
}
};
// Sample test
int main() {
Solution sol;
std::vector<std::string> tokens1 = {"2", "1", "+", "3", "*"};
std::vector<std::string> tokens2 = {"4", "13", "5", "/", "+"};
std::vector<std::string> tokens3 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
std::cout << sol.evalRPN(tokens1) << std::endl; // Output: 9
std::cout << sol.evalRPN(tokens2) << std::endl; // Output: 6
std::cout << sol.evalRPN(tokens3) << std::endl; // Output: 22
return 0;
}
This code correctly evaluates an expression given in Reverse Polish Notation using a stack to perform the necessary arithmetic operations. Each token is processed, and the resulting value is obtained by appropriately managing the stack throughout the evaluation process.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?