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

leetcode - Evaluate Reverse Polish Notation

2014-09-13 10:39 351 查看
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


//经典的数据结构问题,逆波兰表达式的计算,由于没有括号,
//所以,利用stack,每次将遇到的操作数push,当遇到操作符的时候
//pop两次top的元素,然后根本操作符来将这两个元素进行运算。
class Solution {
public:
int evalRPN(std::vector<std::string> &tokens) {
std::stack<int> number;
for(std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); it++)
{
std::string tmp = *it;
if((tmp[0] == '-' && tmp.size() > 1) || ('0' <= tmp[0] && tmp[0] <= '9'))
{
number.push(atoi(tmp.c_str()));
}
else
{
int b = number.top();
number.pop();
int a = number.top();
number.pop();
switch (tmp[0])
{
case '+':number.push(a+b);break;
case '-':number.push(a-b);break;
case '*':number.push(a*b);break;
case '/':if(b == 0) return 0;number.push(a/b);break;
default:
break;
}
}
}
#if 1
std::cout << number.top() << std::endl;
#endif // 1

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