Evaluate Reverse Polish Notation
来源:互联网 发布:深圳gdp首超广州 知乎 编辑:程序博客网 时间:2024/06/08 09:01
Evaluate Reverse Polish Notation
标签(空格分隔): leetcode 算法
题目:
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) { stack<int> s; for (vector<string>::size_type i = 0; i < tokens.size(); ++i) { string& str = tokens[i]; if (str.size()) { if (isdigit(str[0]) || (str[0] == '+' && str.size() > 1) || (str[0] == '-' && str.size() > 1)) { s.push(atoi(str.c_str())); } else if (s.size() >= 2) { int rhs = s.top(); s.pop(); int lhs = s.top(); s.pop(); switch(str[0]) { case '+': s.push(lhs + rhs); break; case '-': s.push(lhs - rhs); break; case '*': s.push(lhs * rhs); break; case '/': if (rhs == 0) { return 0; } else { s.push(lhs / rhs); break; } default: return 0; } } else { return 0; } } } if (s.size() == 1) { int ret = s.top(); s.pop(); return ret; } else { return 0; } }};
0 0
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Hive介绍及部署最详细文档
- 非常详细图文JDK和Tomcat安装和配置的图文教程
- React Native学习资源、开源App和组件
- 树状数组 -- hdu敌兵布阵 -- 树状数组
- Q-Learning实现
- Evaluate Reverse Polish Notation
- 解决MIUI调用系统裁剪照片报错
- Squirrel Simulation
- File
- synchronized和volatile关键字
- 聊聊架构(4)
- 新Android Studio:创建类时,添加作者名和日期等
- PHP实现链表(暂存)
- mysql在linux命令行下导入txt文件