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:
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; } };
相关文章推荐
- [LeetCode] Evaluate Reverse Polish Notation
- LeetCode---2.Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode -- Evaluate Reverse Polish Notation
- leetcode----Evaluate Reverse Polish Notation
- 【Leetcode】Evaluate Reverse Polish Notation答案
- leetcode Evaluate Reverse Polish Notation
- [Leetcode] Evaluate Reverse Polish Notation 逆波兰表达式
- LeetCode(150) Evaluate Reverse Polish Notation
- leetcode解题报告 Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- leetcode:Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation stack 栈
- LeetCode problem 2: Evaluate Reverse Polish Notation
- [leetcode 150] Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- [C++]LeetCode: 98 Evaluate Reverse Polish Notation
- LeetCode OJ Evaluate Reverse Polish Notation