逆波兰表达式求值
首先,先写一个函数用来把字符串中的数字转化为int 的形式
然后,定义一个栈
如果字符串中的是数字就直接转化后入栈
如果是运算符就把栈顶部的两个数字取出来,进行相应的计算
再把得到的ans入栈
最后返回ans
下面附上代码
class Solution {
public:
int strtonums(string s)
{
int nums;
stringstream ss(s);
ss >> nums;
return nums;
}
int evalRPN(vector<string>& tokens)
{
if (tokens.size() == 1)
{
return strtonums(tokens[0]);
}
stack<int> stack1;
int ans;
for (int i = 0; i<tokens.size(); i++)
{
if (tokens[i] == "+")
{
int a = stack1.top();
stack1.pop();
int b = stack1.top();
stack1.pop();
ans = a + b;
stack1.push(ans);
}
else if (tokens[i] == "-")
{
int a = stack1.top();
stack1.pop();
int b = stack1.top();
stack1.pop();
ans = b - a;
stack1.push(ans);
}
else if (tokens[i] == "/")
{
int a = stack1.top();
stack1.pop();
int b = stack1.top();
stack1.pop();
ans = b / a;
stack1.push(ans);
}
else if (tokens[i] == "*")
{
int a = stack1.top();
stack1.pop();
int b = stack1.top();
stack1.pop();
ans = a*b;
stack1.push(ans);
}
else
{
int r = strtonums(tokens[i]);
stack1.push(r);
}
}
return ans;
}
};