LeetCode(150) Evaluate Reverse Polish Notation
2014-12-24 17:51
225 查看
题目如下:
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的基础型题目。
我的代码:
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的基础型题目。
我的代码:
//80ms class Solution { public: int evalRPN(vector<string> &tokens) { int i = 0; int operand1 = 0; int operand2 = 0; stack<int> operand_stack; while (i < tokens.size()) { if (tokens[i] == "+") { operand1 = operand_stack.top(); operand_stack.pop(); operand2 = operand_stack.top(); operand_stack.pop(); operand_stack.push(operand2 + operand1); } else if (tokens[i] =="-") { operand1 = operand_stack.top(); operand_stack.pop(); operand2 = operand_stack.top(); operand_stack.pop(); operand_stack.push(operand2 - operand1); } else if(tokens[i] == "*") { operand1 = operand_stack.top(); operand_stack.pop(); operand2 = operand_stack.top(); operand_stack.pop(); operand_stack.push(operand2 * operand1); } else if (tokens[i] == "/") { operand1 = operand_stack.top(); operand_stack.pop(); operand2 = operand_stack.top(); operand_stack.pop(); operand_stack.push(operand2 / operand1); } else { operand1 = atoi(tokens[i].c_str()); operand_stack.push(operand1); } i++; } return operand_stack.top(); } };
相关文章推荐
- leetcode150 Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- leetcode150 Evaluate Reverse Polish Notation
- leetcode_150 Evaluate Reverse Polish Notation
- LeetCode: Evaluate Reverse Polish Notation [150]
- [LeetCode 150] Evaluate Reverse Polish Notation
- leetcode(150):Evaluate Reverse Polish Notation
- leetcode[150] Evaluate Reverse Polish Notation
- LeetCode 150 — Evaluate Reverse Polish Notation(C++ Java Python)
- Leetcode 150:Evaluate Reverse Polish Notation
- [LeetCode]150 Evaluate Reverse Polish Notation
- LeetCode150 Evaluate Reverse Polish Notation
- [LeetCode]题解(python):150-Evaluate Reverse Polish Notation
- Leetcode#150 Evaluate Reverse Polish Notation
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- leetcode-150-Evaluate Reverse Polish Notation
- leetcode 150: Evaluate Reverse Polish Notation
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- [Leetcode 150, Medium] Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现