LeetCode- Evaluate Reverse Polish Notation
来源:互联网 发布:软件beta版已过期 编辑:程序博客网 时间:2024/06/10 18:08
题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
数学表达式的 逆式波兰记法。
答案:
class Solution {public: int evalRPN(vector<string>& tokens) { stack<int> cache; for(int i = 0; i < tokens.size(); i++){ if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="/"||tokens[i]=="*"){ int num1 = cache.top(); cache.pop(); int num2 = cache.top(); cache.pop(); cache.push(caculate(num1,num2,tokens[i])); } else{ cache.push(std::atoi(tokens[i].c_str())); } } int num = cache.top(); return num; } int caculate(int n1,int n2,string op){if(op == "+")return n1 + n2;if(op == "-")return n2 - n1;if(op == "*")return n1 * n2;if(op == "/")return n2 / n1;}};
说明:
1. c++的STL很强大,类似stack,list,map等都有集成。
2.C++string转int:很好用的方法:std::atoi(str.c_str());
3.int转string:
char * itoa ( int value, char * str, int base );
注意返回的是char类型。base是其转换的进制,如 二进制,八进制,十进制。
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
- PAT (Advanced Level) Practise 1062 Talent and Virtue (25)
- hbase 介绍
- 2016.3.17__ JavaScript基础_1__第十二天
- 后缀表达式求值
- Spring mybatis无法注入问题解决一例
- LeetCode- Evaluate Reverse Polish Notation
- PAT (Advanced Level) Practise 1063 Set Similarity (25)
- iOS设置navigationBar背景透明
- WIN64上一种只需修改函数6个字节的INLINE HOOK方法
- JSON与null的解惑
- C++: 模拟实现类bitset
- Understanding LSTM Networks
- 搜索引擎原理 – 正排索引、倒排索引以及齐普夫法则
- ios学习资料