首页 > 代码库 > compute post expression

compute post expression

#include<iostream>
#include<stack>
#include<string>
using namespace std;

//post expression compute
int compute(int num1, int num2, char op)
{
	if (op == ‘+‘)
		return num1 + num2;
	else if (op == ‘-‘)
		return num1 - num2;
	else if (op == ‘*‘)
		return num1*num2;
	else if (op == ‘/‘)
		return num2 / num1;
}

int main()
{
	stack<char>num;
	string s;
	cin >> s;

	for (int i = 0; i<s.length(); i++)
	{
		if ((s[i] == ‘0‘ || s[i] == ‘1‘ || s[i] == ‘2‘ || s[i] == ‘3‘ || s[i] == ‘4‘ || s[i] == ‘5‘ || s[i] == ‘6‘ || s[i] == ‘7‘ || s[i] == ‘8‘ || s[i] == ‘9‘))
			num.push(s[i]);
		else
		{
			int num1 = num.top() - ‘0‘;
			num.pop();
			int num2 = num.top() - ‘0‘;
			num.pop();
			char result = compute(num1, num2, s[i]) + ‘0‘;
			num.push(result);
		}
	}

	cout << num.top()-‘0‘ << endl;

	return 0;
}

  

compute post expression