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

Leetcode: Evaluate Reverse Polish Notation

2014-06-28 21:52 190 查看
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> st;
int result = 0;
int op1 = 0, op2 = 0;

for (vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) {
if (*it == "+") {
op1 = st.top();
st.pop();
op2 = st.top();
st.pop();
result = op1 + op2;
st.push(result);
} else if (*it == "-") {
op1 = st.top();
st.pop();
op2 = st.top();
st.pop();
result = op2 - op1;
st.push(result);
} else if (*it == "*") {
op1 = st.top();
st.pop();
op2 = st.top();
st.pop();
result = op1 * op2;
st.push(result);
} else if (*it == "/") {
op1 = st.top();
st.pop();
op2 = st.top();
st.pop();
result = op2 / op1;
st.push(result);
} else {
st.push(atoi((*it).c_str()));
}
}

result = st.top();

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