LeetCode:Evaluate Reverse Polish Notation
2013-11-28 22:42
417 查看
题目链接
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are
Some examples:
分析:这一题就是写程序计算逆波兰式的结果,遍历表达式,碰到操作数入栈,碰到操作符就从栈顶取出两个操作数,再将计算后的结果入栈,最后栈中剩余的唯一操作数就是计算结果。 本文地址
【版权声明】转载请注明出处:/article/4879671.html
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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = tokens.size(); stack<int> S; for(int i = 0; i < len; i++) { if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int op2 = S.top(); S.pop(); int op1 = S.top(); S.pop(); S.push( op(op1, op2, tokens[i][0]) ); } else S.push(stoi(tokens[i])); } return S.top(); } int op(int op1, int op2, char optor) { if(optor == '+')return op1 + op2; else if(optor == '-')return op1 - op2; else if(optor == '*')return op1 * op2; else return op1 / op2; } };
【版权声明】转载请注明出处:/article/4879671.html
相关文章推荐
- LeetCode 150. Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation--LeetCode
- evaluate-reverse-polish-notation(Leetcode)
- [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_2 Evaluate Reverse Polish Notation 逆波兰表达式
- 【LeetCode-面试算法经典-Java实现】【150-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 | 分析逆波兰式 | Medium
- leetcode[150]Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation
- LeetCode150:Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation