<题目表述>
根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。给定表达式总是有效的。
示例 1:
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
<原题链接>
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
<思路>
该题按照逆波兰的算法规则书写代码即可通过。
【注】关于如何将一个中序表达式转换为逆波兰形式详见我的另一篇博客。
<样例代码>
#include<iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;
class Solution {
private:
int toInt(string str);
int exec(int a, int b, char ch);
public:
int evalRPN(vector<string>& tokens) {
stack<int> num;
for (int i = 0; i < tokens.size(); i++)
{
if ((tokens[i][0] >= '0' && tokens[i][0] <= '9') ||
(tokens[i][0] == '-' && tokens[i][1] >= '0' && tokens[i][1] <= '9'))
num.push(toInt(tokens[i]));
else
{
int a = num.top(); num.pop();
int b = num.top(); num.pop();
num.push(exec(b, a, tokens[i][0]));
}
}
return num.top();
}
};
int Solution::toInt(string str)
{
int ans = 0, i = 0;
bool flag = false;
if (str[0] == '-')
{
i = 1;
flag = true;
}
for (; i < str.length(); i++)
ans = ans * 10 + (str[i] - 48);
if (flag)
return -ans;
return ans;
}
int Solution::exec(int a, int b, char ch)
{
switch (ch)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
break;
}
return 0;
}