标签:24 int top pop 2021.9 push ints 求值 表达式
题目描述:
根据 逆波兰表示法,求表达式的值。
有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
方法一:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> ints;
for (string c : tokens)
{
if (c == "+")
{
int x = ints.top();
ints.pop();
int y = ints.top();
ints.pop();
ints.push(x + y);
}
else if (c == "-")
{
int x = ints.top();
ints.pop();
int y = ints.top();
ints.pop();
ints.push(y - x);
}
else if (c == "*")
{
int x = ints.top();
ints.pop();
int y = ints.top();
ints.pop();
ints.push(x * y);
}
else if (c == "/")
{
int x = ints.top();
ints.pop();
int y = ints.top();
ints.pop();
ints.push(y / x);
}
else
{
int a = stoi(c); //将字符串转换为数字
ints.push(a);
}
}
return ints.top();
}
};
以前老师让写过求解任意一个表达式的值,所以相对来说这题还算简单。
题目用到的字符串转换为数字的函数为stoi()。
标签:24,int,top,pop,2021.9,push,ints,求值,表达式 来源: https://blog.csdn.net/weixin_52629904/article/details/120462084
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。