您的位置:首页 > 编程语言 > Lua

leetcode.150. Evaluate Reverse Polish Notation

2016-05-10 20:47 477 查看
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<string>& tokens) {
int result = 0;
int i;
stack<int> opd;         //存储操作数
int size = tokens.size();
for(i=0;i<size;i++)
{
if(tokens[i]=="*")
{
int rOpd = opd.top();   //右操作数
opd.pop();
int lOpd = opd.top();  //左操作数
opd.pop();
result = lOpd*rOpd;
opd.push(result);
}
else if(tokens[i]=="/")
{
int rOpd = opd.top();
opd.pop();
int lOpd = opd.top();
opd.pop();
result = lOpd/rOpd;
opd.push(result);
}
else if(tokens[i]=="+")
{
int rOpd = opd.top();
opd.pop();
int lOpd = opd.top();
opd.pop();
result = lOpd+rOpd;
opd.push(result);
}
else if(tokens[i]=="-")
{
int rOpd = opd.top();
opd.pop();
int lOpd = opd.top();
opd.pop();
result = lOpd-rOpd;
opd.push(result);
}
else
{
opd.push(atoi(tokens[i].c_str()));
}
}
return opd.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: