evaluate-reverse-polish-notation
2016-07-17 18:03
399 查看
题目描述
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> stack;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(a + b);
} else if (tokens.at(i) == "-") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(b - a);
} else if (tokens.at(i) == "*") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(a * b);
} else if (tokens.at(i) == "/") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(b / a);
} else {
//进行将string类型转换为int 类型
stack.push(stoi(tokens[i]));
}
}
return stack.top();
}
};
相关文章推荐
- Linux C函数参考手册(PDF版)
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#数据结构之顺序表(SeqList)实例详解
- C# partial关键字说明
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- Lua教程(十七):C API简介
- 简单谈谈lua和c的交互
- Lua教程(七):数据结构详解
- C#用链式方法表达循环嵌套
- C#算法函数:获取一个字符串中的最大长度的数字
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- C#数据结构之队列(Quene)实例详解