逆波兰表达式求值
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +
, -
, *
, /
。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
一下为代码
#include "stdio.h"
#include "string"
#include "vector"
#include "stack"
#include "assert.h"
using namespace std;
class Solution {
private:
stack<int>s;
public:
/*
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
int evalRPN(vector<string> tokens) {
if(tokens.size()<=0)
{
return 0;
}
for(int i=0;i<tokens.size();i++)
{
int a1=atoi(tokens[i].c_str());//这里atoi会把非数字的字符转换为0!一定要注意
if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/")
s.push(stoi(tokens[i]));
else
{
assert(s.size()>=2);//断言
int num2=s.top();//后进先出,不要弄错
s.pop();
int num1=s.top();
s.pop();
if(tokens[i]=="+")
{
num1=num1+num2;
s.push(num1);
}
if(tokens[i]=="-")
{
num1=num1-num2;
s.push(num1);
}
if(tokens[i]=="*")
{
num1=num1*num2;
s.push(num1);
}
if(tokens[i]=="/")
{
num1=num1/num2;
s.push(num1);
}
}
}
return s.top();
}
};