Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
The infix expression "5 + ((1 + 2) * 4) − 3" can be written down like this in RPN:
- 5 1 2 + 4 * + 3 -
#include
using namespace std;
#include
#include
class Solution {
public:
int evalRPN(vector
&tokens) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
stack
result; for (int i = 0; i < tokens.size(); i++) { string token = tokens[i]; if (token.size() == 1 && isdigit(token[0]) == 0) { //operator int right = result.top(); //先是右操作数 result.pop(); int left = result.top(); result.pop(); int answer = 0; switch (token[0]) { case '+': answer = left + right; break; case '-': answer = left - right; break; case '*': answer = left * right; break; case '/': answer = left / right; break; default: break; } result.push(answer); } else { result.push(stringToInt(token)); } } return result.top(); } int stringToInt(string str) { if (str[0] == '-') { return -stringToInt(str.substr(1)); } int result = 0; for (int i = 0; i < str.size(); i++) { result = result * 10 + (str[i] - '0'); } return result; } }; int main() { string token_array[] = {"2", "1", "+", "3", "*"}; vector
tokens; for (int i = 0; i < 5; i++) { tokens.push_back(token_array[i]); } Solution so; cout << so.evalRPN(tokens) << endl; return 0; }