leetCode-逆波兰表达式求值

2014-11-03  本文已影响577人  windgo

开始刷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

<code>
class Solution {
public:
int evalRPN(vector<string> &tokens) {
vector<int> opNumberVector;
for(int i=0;i<tokens.size();i++){
if(tokens[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=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//numbers
{
opNumberVector.push_back(atoi(tokens[i].c_str()));
}

    }
    return opNumberVector[0];
}

};

上一篇下一篇

猜你喜欢

热点阅读