/*
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
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
*/
简单题 使用栈模拟 逆波兰表达式的计算过程即可
应注意使用streamstring 做多次类型转换时 要使用clear()方法
部分代码写的比较繁琐
/*
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 <stack>
#include <string>
#include <cstdio>
#include <sstream>
using namespace std;
class Solution{
public:
int evalRPN(vector<string> &tokens)
{
stack<string> exp;
int res;
string op1,op2;
int num1,num2;
stringstream ss;
for(int i = 0;i < tokens.size();i++)
{
switch (tokens[i].at(0))
{
case '+':
{
ss.clear();
op2 = exp.top();
ss << op2;
ss >> num2;
ss.clear();
exp.pop();
op1 = exp.top();
ss << op1;
ss >> num1;
exp.pop();
res = num1+num2;
ss.clear();
ss << res;
ss >> op1;
exp.push(op1);
}
break;
case '-':
{
if(tokens[i].length() == 1 )
{
ss.clear();
op2 = exp.top();
ss << op2;
ss >> num2;
exp.pop();
op1 = exp.top();
ss.clear();
ss << op1;
ss >> num1;
exp.pop();
res = num1-num2;
ss.clear();
ss << res;
ss >> op1;
exp.push(op1);
}
else
exp.push(tokens[i]);
}
break;
case '*':
{
op2 = exp.top();
ss.clear();
ss << op2;
ss >> num2;
exp.pop();
op1 = exp.top();
ss.clear();
ss << op1;
ss >> num1;
exp.pop();
res = num1*num2;
ss.clear();
ss << res;
ss >> op1;
exp.push(op1);
}
break;
case '/':
{
op2 = exp.top();
ss.clear();
ss << op2;
ss >> num2;
exp.pop();
op1 = exp.top();
ss.clear();
ss << op1;
ss >> num1;
exp.pop();
res = num1/num2;
ss.clear();
ss << res;
ss >> op1;
exp.push(op1);
}
break;
default:
exp.push(tokens[i]);
}
}
op1 = exp.top();
ss.clear();
ss << op1;
ss >> res;
return res;
}
};
int main()
{
vector<string> s;
s.push_back("3");
s.push_back("-4");
s.push_back("+");
Solution a;
cout << a.evalRPN(s)<< endl;
return 0;
}