开始刷leetCode, 算法一直没有努力学习过, 以后不管是否能用到, 作为一个计算机专业的, 还是补一下课吧.
- 计算一个逆波兰数学表达式(操作数在前面,操作符在后面)的值, 这类题目当年在学编译原理的时候应该会遇到;
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
- 思路: 用一个栈来存操作数, 遇到一个操作符就取出两个操作数进行计算, 将计算结果再放进操作数栈中.
class Solution {
public:
int evalRPN(vector
vector
for(int i=0;i
{
int a=opNumberVector.back();
opNumberVector.pop_back();
int b=opNumberVector.back();
opNumberVector.pop_back();
int r=a+b;
opNumberVector.push_back(r);
}
else if(tokens[i]=="-")
{
int a=opNumberVector.back();
opNumberVector.pop_back();
int b=opNumberVector.back();
opNumberVector.pop_back();
int r=b-a;
opNumberVector.push_back(r);
}
else if(tokens[i]=="")
{
int a=opNumberVector.back();
opNumberVector.pop_back();
int b=opNumberVector.back();
opNumberVector.pop_back();
int r=ab;
opNumberVector.push_back(r);
}
else if(tokens[i]=="/")
{
int a=opNumberVector.back();
opNumberVector.pop_back();
int b=opNumberVector.back();
opNumberVector.pop_back();
int r=b/a;
opNumberVector.push_back(r);
}
else//numbers
{
opNumberVector.push_back(atoi(tokens[i].c_str()));
}
}
return opNumberVector[0];
}
};