LEETCODE: Evaluate Reverse Polish Notation
来源:互联网 发布:数据库全部概念 编辑:程序博客网 时间:2024/06/05 19:09
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: bool isFlag(string str) { if(str.length() != 1) return false; if(str[0] == '-' || str[0] == '+' || str[0] == '/' || str[0] == '*') return true; return false; } int calculate(int left, int right, string flag) { if(flag[0] == '+') return left + right; if(flag[0] == '-') return left - right; if(flag[0] == '*') return left * right; if(flag[0] == '/') return left / right; return 0; } int stringToNumber(string str) { int number = 0; int flag = 1; for(int ii = 0; ii < str.length(); ii ++) { if(ii == 0) { if(str[0] == '-') { flag = -1; continue; } else if(str[0] == '+') { continue; } } number = number * 10 + str[ii] - '0'; } return number * flag; } int evalRPN(vector<string> &tokens) { if(tokens.size() == 0) return 0; stack<int> st; for(int ii = 0; ii < tokens.size(); ii ++) { if(isFlag(tokens[ii])) { int right = st.top(); st.pop(); int left = st.top(); st.pop(); int current = calculate(left, right, tokens[ii]); st.push(current); } else { st.push(stringToNumber(tokens[ii])); } } return st.top(); }};
0 0
- Evaluate Reverse Polish Notation | leetcode
- 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
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【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
- [HTML]初识HTML
- js url截取文件名
- javascript介绍
- 深入剖析智能指针 shared_ptr
- 一个简单的登陆注册系统
- LEETCODE: Evaluate Reverse Polish Notation
- android用最简单的方法实现QQ5.0的侧边栏滑动效果
- 用户名 不在 sudoers文件中,此事将被报告。
- jquery $.fn
- Framelayout布局中嵌套多个布局layout的显示
- 1023.Have Fun with Numbers
- C#中的线程(一)入门
- [Hive]求两个集合的减集
- in and of itself