根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 :
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 :
输入: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = 22
解题思路:
将数字入栈,遇到符号则将两个元素出栈进行运算,并将计算结果入栈
判断数字:
第一个字符为数字,则此元素就为数字,因为有负数,所以当元素长度不为1时,此时也是数字
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cctype>
#include <cstdlib>
using namespace std;
int evalRPN(vector<string>& tokens){
stack<int> tmp;
int a, b;
for (auto & vsi : tokens){
if (isdigit(vsi[0]) || vsi.size() > 1){
tmp.push(atoi(vsi.c_str()));
}
else{
a = tmp.top();
tmp.pop();
b = tmp.top();
switch (vsi[0])
{
case '+':
tmp.top() = b + a;
break;
case '-':
tmp.top() = b - a;
break;
case '*':
tmp.top() = b * a;
break;
case '/':
tmp.top() = b / a;
break;
default:
break;
}
}
}
return tmp.top();
}
int main(){
vector<string> vs{ "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" };
cout << evalRPN(vs);
system("pause");
return 0;
}