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
Hide Tags
题目是用 stack 维护一个公式的进出,判断方法还可以,开始忘记数可能为负,后面改进了。
#include <stack>
#include <iostream>
#include <string>
#include <vector>
using namespace std; class Solution {
public:
int evalRPN(vector<string> &tokens) {
int n = tokens.size();
stack<int > tmp;
for(int i=;i<n;i++){
if(tokens[i][]>=''&&tokens[i][]<=''){
tmp.push( helpFun(tokens[i]) );
continue;
}
if(tokens[i][]=='-'&&tokens[i][]!='\0'){
tmp.push( helpFun( tokens[i]));
continue;
}
int rgt = tmp.top();
tmp.pop();
int lft = tmp.top();
tmp.pop();
switch (tokens[i][]){
case '+':
tmp.push( lft + rgt );
break;
case '-':
tmp.push(lft - rgt);
break;
case '*':
tmp.push(lft * rgt);
break;
case '/':
tmp.push(lft / rgt);
break;
}
}
return tmp.top();
} int helpFun(string str)
{
int sum = ,i = ;
if (str[]=='-')
i = ;
for(;i<str.length();i++)
sum = sum*+str[i]-'';
return str[]=='-'?-sum:sum;
}
}; int main()
{
vector<string> tokens{"","-4","+"};
Solution sol;
cout<<sol.evalRPN(tokens)<<endl;
// for(int i=0;i<tokens.size();i++)
// cout<<tokens[i]<<endl;
return ;
}