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

LeetCode Evaluate Reverse Polish Notation

2014-07-15 15:23 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

class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> myStack;
vector<string>::iterator iter = tokens.begin();
for (; iter != tokens.end(); iter++) {
if (*iter != "+" && *iter != "-" && *iter != "*" && *iter != "/") {
int iot = atoi((*iter).c_str());
myStack.push(iot);
} else{
int ia, ib;
ib = myStack.top();
myStack.pop();
ia = myStack.top();
myStack.pop();

if (*iter == "+") {
ia += ib;
myStack.push(ia);
}
else if (*iter == "-") {
ia -= ib;
myStack.push(ia);
}
else if (*iter == "*") {
ia *= ib;
myStack.push(ia);
}
else if (*iter == "/") {
ia /= ib;
myStack.push(ia);
}
}
}
return myStack.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode