[Blue Bridge Cup] Exam Training 2013 C++A Group Question 6 Inverse Polish Expression

Inverse Polish expression

Normal expressions are called infix expressions. The operator is in the middle, which is mainly for people to read. It is not convenient to solve by machine.
For example: 3 + 5 * (2 + 6)-1
Moreover, it is often necessary to use parentheses to change the order of operations.
On the contrary, if it is expressed by inverse Polish expression (prefix expression), the above formula is expressed as:
-+ 3 * 5 + 2 6 1 The
parentheses are no longer needed, and the machine can easily solve it by recursive method.
For simplicity, we assume:
1. There are only three operators +-*
2. Each operand is a non-negative integer less than 10 The
following program evaluates an inverse Polish representation string.
The return value is an array: the first element represents the evaluation result, and the second element represents the number of characters it has parsed. Please analyze the code logic, and guess the code at the underline, and submit it through the web page.
Note: Only use the missing code as the answer, and do not fill in extra codes, symbols or explanatory text! !

struct EV
{
int result; //计算结果 
int n; //消耗掉的字符数 
};

struct EV evaluate(char* x)
{
struct EV ev = {0,0};
struct EV v1;
struct EV v2;

if(*x==0) return ev;

if(x[0]>='0' && x[0]<='9'){
ev.result = x[0]-'0';
ev.n = 1;
return ev;
}

v1 = evaluate(x+1);
v2 = _________; //填空位置

if(x[0]=='+') ev.result = v1.result + v2.result;
if(x[0]=='*') ev.result = v1.result * v2.result;
if(x[0]=='-') ev.result = v1.result - v2.result;
ev.n = 1+v1.n+v2.n;

return ev;
}

 Answer: evaluate(x+v1.n+1)

 

Problem analysis

Guess, considering that the variables given in the title have unused variables, v1.n, the results given in each step must be useful, especially given the return variable received, then the following steps use the variable May be big, you can try

#include <iostream>
using namespace std;

struct EV{
	int result; //计算结果 
	int n; //消耗掉的字符数 
};

struct EV evaluate(char* x)
{
	struct EV ev = {0,0};
	struct EV v1;
	struct EV v2;
	
	if(*x == 0) return ev;
	
	if(x[0]>='0' && x[0]<='9'){
		ev.result = x[0] - '0'; //字符转数字 
		ev.n = 1;
		return ev;
	}

	v1 = evaluate(x+1);
//	v2 = _________; //填空位置
	v2 = evaluate(x+v1.n+1);
	
	if(x[0]=='+') ev.result = v1.result + v2.result;
	if(x[0]=='*') ev.result = v1.result * v2.result;
	if(x[0]=='-') ev.result = v1.result - v2.result;
	ev.n = 1 + v1.n + v2.n;
	
	return ev;
}

int main(int argc, char** argv) {
	string str = "-+3*5+261";
	const EV &ev = evaluate((char*)(str.c_str()));
	cout << ev.result << endl;
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/115139746