简介
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, , /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to
a result and there won’t be any divide by zero operation.
Example 1:
Input: [“2”, “1”, “+”, “3”, ""]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
解题思路
这是逆波兰式(后缀表达式)的计算。
判断若为数字,将其压入数字栈,若为运算符,则把栈顶两个数字压出,进行运算后,再把新计算的数压入栈。最后栈内只剩一个数,即为运算结果。
代码
#include <iostream>
#include<string>
#include<vector>
#include<stack>
#include <sstream>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int temp;
int a, b;
for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++)
{
if(*it == "+" || *it == "-" || *it == "*" || *it == "/" && num.empty() != true)
{
a = num.top();
num.pop();
b = num.top();
num.pop();
if(*it == "+")
{
temp = a + b;
num.push(temp);
}
else if(*it == "-")
{
temp = b - a;
num.push(temp);
}
else if(*it == "*")
{
temp = b * a;
num.push(temp);
}
else
{
temp = b / a;
num.push(temp);
}
}
else
{
int n;
n = StrToInt(*it);
num.push(n);
}
}
return num.top();
}
private:
stack<int> num;
int StrToInt(string str) //字符串转换为整型
{
stringstream ss;
ss<<str;
int i;
ss>>i;
return i;
}
};
int main()
{
vector<string> str;
//string i;
str.push_back("10");
str.push_back("6");
str.push_back("9");
str.push_back("3");
str.push_back("+");
str.push_back("-11");
str.push_back("*");
str.push_back("/");
str.push_back("17");
str.push_back("+");
str.push_back("5");
str.push_back("+");
Solution su;
cout << su.evalRPN(str);
return 0;
}