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

LeetCode题解:Evaluate Reverse Polish Notation

2013-11-28 03:43 441 查看

Evaluate Reverse Polish Notation

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

思路:

我真的不知道为什么LeetCode会出这么简单的题目。

题解:

class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> numeric;

for(auto& t : tokens)
{
if (isdigit(t[0]) || t.size()>1)
numeric.push(atoi(t.c_str()));
else
{
int o1, o2;
o2 = numeric.top();
numeric.pop();
o1 = numeric.top();
numeric.pop();

switch(t[0])
{
case '+':
numeric.push(o1 + o2);
break;
case '-':
numeric.push(o1 - o2);
break;
case '*':
numeric.push(o1 * o2);
break;
case '/':
numeric.push(o1 / o2);
break;
}
}
}

return numeric.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: