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
#include<iostream> #include<vector> #include<string> #include<iterator> #include<stack> #include<stdlib.h> #include <sstream> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { stack<string> s; string token; for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++) { token = *it; if (!is_operator(*it)) { s.push(*it); } else { if (s.empty()) return 0;//验证表达式是否正确 int y = string_to_number(s.top()); s.pop(); if (s.empty()) return 0; int x = string_to_number(s.top()); s.pop(); if (token[0] == '+') x += y; else if (token[0] == '-') x -= y; else if (token[0] == '*') x *= y; else { if(y == 0) return 0;//除数不能为零 x /= y; } s.push(n_to_string(x)); } } return string_to_number(s.top()); } private: bool is_operator(const string &op) { return op.size() == 1 && string("+-*/").find(op) != string::npos; } int string_to_number(string &s) { int Result; istringstream convert(s); // stringstream used for the conversion constructed with the contents of 'Text' // ie: the stream will start containing the characters of 'Text' if ( !(convert >> Result) ) //give the value to 'Result' using the characters in the stream Result = 0; //if that fails set 'Result' to 0 return Result; } string n_to_string(int num) { string Result; // string which will contain the result ostringstream convert; // stream used for the conversion convert << num; // insert the textual representation of 'Number' in the characters in the stream Result = convert.str(); // set 'Result' to the contents of the stream // 'Result' now is equal to "123" return Result; } }; int main() { Solution evaluate; vector<string> rp_Expression; int value; string expression; while(cin >> expression) { rp_Expression.push_back(expression); } cout << "rp_Expression.size = " << rp_Expression.size() << endl; cout << "rp_Expression.front = " << rp_Expression.front() << endl; cout << "rp_Expression.back = " << rp_Expression.back() << endl; value = evaluate.evalRPN(rp_Expression); cout << value << endl; return 0; }
注意事项:
1、验证表达式的正确性
2、除数不能为零
3、加法与乘法满足交换律,减法与除法不满足交换律,因此将出栈的两个操作数调换进行加减乘除运算位置即可。