逆波兰表达式求值

根据 逆波兰表示法,求表达式的值,有效的运算符包括 + , - , * , / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

逆波兰表达式是一种后缀表达式,运算符写在后面。

 解题思路:按照顺序遍历数组,当数组中元素为数字字符串时,将字符串转化为整型后入栈;当数组中元素为运算符时,弹出栈顶两个元素进行运算,并将结果入栈,最终结果为栈内唯一一个元素,进行返回。

实现代码如下:

//逆波兰表达式求值
int evalRPN(vector<string>& tokens) {
	stack<int> st;
	for(int i = 0; i<tokens.size(); i++) {
		if (tokens[i] == "+") {
			int n1 = st.top();
			st.pop();
			int n2 = st.top();
			st.pop();
			st.push(n2+n1);
		}
		else if (tokens[i] == "-") {
			int n1 = st.top();
			st.pop();
			int n2 = st.top();
			st.pop();
			st.push(n2-n1);
		}
		else if (tokens[i] == "*") {
			int n1 = st.top();
			st.pop();
			int n2 = st.top();
			st.pop();
			st.push(n2*n1);
		}
		else if (tokens[i] == "/") {
			int n1 = st.top();
			st.pop();
			int n2 = st.top();
			st.pop();
			st.push(n2/n1);
		}
		else {
			int n = stoi(s[i]);
			st.push(n);
		}
	}
	return st.top();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++逆波兰表达式求值是一种常见的数学表达式求值方法,也被称为后缀表达式求值逆波兰表达式是一种不需要括号来标识优先级的表达式表示方法,它将操作符放在操作数的后面。 在C++中,可以通过使用来实现逆波兰表达式求值。具体步骤如下: 1. 创建一个空用于存储操作数。 2. 从左到右遍历逆波兰表达式的每个元素。 3. 如果当前元素是操作数,则将其压入中。 4. 如果当前元素是操作符,则从中弹出两个操作数,并根据操作符进行计算,将计算结果压入中。 5. 重复步骤3和步骤4,直到遍历完整个逆波兰表达式。 6. 最后,中剩下的唯一元素就是逆波兰表达式的求值结果。 下面是一个示例代码,用于实现逆波兰表达式求值: ```cpp #include <iostream> #include <stack> #include <string> #include <sstream> using namespace std; int evaluateRPN(string expression) { stack<int> operands; stringstream ss(expression); string token; while (getline(ss, token, ' ')) { if (token == "+" || token == "-" || token == "*" || token == "/") { int operand2 = operands.top(); operands.pop(); int operand1 = operands.top(); operands.pop(); if (token == "+") { operands.push(operand1 + operand2); } else if (token == "-") { operands.push(operand1 - operand2); } else if (token == "*") { operands.push(operand1 * operand2); } else if (token == "/") { operands.push(operand1 / operand2); } } else { operands.push(stoi(token)); } } return operands.top(); } int main() { string expression = "5 + 3 *"; int result = evaluatePN(expression); cout << "Result: " << result << endl; return 0; } ``` 以上代码中,我们使用了一个来存储操作数,并通过stringstream来逐个读取逆波兰表达式中的元素。如果遇到操作符,则从中弹出两个操作数进行计算,并将结果压入中。最后,中剩下的唯一元素就是逆波兰表达式的求值结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值