计算表达式(falg x y)

计算表达式(falg x y),flag可以是+ ,-,^ ,其中^是一元运算符,要求判断表达式的合法性


#include<string>
using namespace std;

string str;
int n;
int b = 1;


//思路
//判断( + x y)  注意x和y可能是数字也可能是一个运算 都需要判断
//或者( * x y)
//或者( ^ x )
int cal()
{
	if (b >= n) return -1;
	char ch = str[b];
	if (ch != '^' && ch != '+' && ch != '*') 
		return -1;
	++b;

	if (b >= n || str[b] != ' ') 
		return -1;
	++b;
	int x = 0;

	if (b >= n) 
		return -1;
	else if (str[b] == '(')   //再次出现左括号 退出
	{
		++b;
		x = cal();
		if (x == -1) 
			return -1;
		++b;
	}
	else if (str[b] < '0' || str[b] > '9') 
		return -1;
	else
	{
		while (str[b] >= '0' && str[b] <= '9')   //算出左边的数字
		{
			x *= 10;
			x += str[b] - '0';
			++b;
		}
	}
	if (b >= n) 
		return -1;
	else if (ch == '^')      //如果符号是 ^
		return x + 1;

	if (str[b] != ' ') 
		return -1;
	++b;
	int y = 0;
	if (b >= n) 
		return -1;
	else if (str[b] == '(')
	{
		++b;
		y = cal();
		if (y == -1) return -1;
		++b;
	}
	else if (str[b] < '0' || str[b] > '9') return -1;
	else
	{
		while (str[b] >= '0' && str[b] <= '9')
		{
			y *= 10;
			y += str[b] - '0';
			++b;
		}
	}

	if (str[b] != ')')
		return -1;
	if (ch == '+') 
		return x + y;
	else 
		return x * y;
}

int main()
{
	getline(cin, str);
	n = str.size();
	int ans = -1;
	if (str[0] == '(') ans = cal();
	printf("%d", ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Alatebloomer/article/details/81772696