[LeetCode] Evaluate Reverse Polish Notation
2014-03-12 21:50
330 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are
Some examples:
Solution:
需要注意operand为负数的情况。
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
Solution:
需要注意operand为负数的情况。
class Solution { public: int stringToInt(string s) { if(s.length() == 0) return 0; int p = 1; if(s[0] == '-') { p = -1; s = s.substr(1, s.length() - 1); } int ans = s[0] - '0'; for(int i = 1;i < s.length();i++) ans = ans * 10 + s[i] - '0'; return ans * p; } int evalRPN(vector<string> &tokens) { int len = tokens.size(), ans = 0; int *operand = new int[len + 1], operandNum = 0; memset(operand, 0, (len + 1) * sizeof(int)); int res = 0; // 0 for num, 1 +, 2 -, 3 *, 4 / for(int i = 0;i < len;i++) { if(tokens[i] == "+") { operand[operandNum - 2] = operand[operandNum - 2] + operand[operandNum - 1]; operandNum--; } else if(tokens[i] == "-") { operand[operandNum - 2] = operand[operandNum - 2] - operand[operandNum - 1]; operandNum--; } else if(tokens[i] == "*") { operand[operandNum - 2] = operand[operandNum - 2] * operand[operandNum - 1]; operandNum--; } else if(tokens[i] == "/") { operand[operandNum - 2] = operand[operandNum - 2] / operand[operandNum - 1]; operandNum--; } else { int op = stringToInt(tokens[i]); operand[operandNum++] = op; } } return operand[0]; } };
相关文章推荐
- [LeetCode] Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- 【leetcode】150. Evaluate Reverse Polish Notation
- LeetCode 2 Evaluate Reverse Polish Notation
- LeetCode--evaluate-reverse-polish-notation
- 【leetcode】Evaluate Reverse Polish Notation
- LeetCode:150. Evaluate Reverse Polish Notation(逆波兰表达式)
- LeetCode--150. Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- Leetcode 150. Evaluate Reverse Polish Notation
- leetcode day1 -- Reverse Words in a String && Evaluate Reverse Polish Notation && Max Points on a Li
- leetcode 150: Evaluate Reverse Polish Notation
- LeetCode之Evaluate Reverse Polish Notation
- 【Leetcode】Evaluate Reverse Polish Notation JAVA
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation(LeetCode)
- Leetcode (10) Evaluate Reverse Polish Notation (计算逆波兰表示法多项式)
- 【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)
- leetcode题解-150. Evaluate Reverse Polish Notation