华为机试 - 火星计算器

火星计算器:
   火星人使用运算符:@ # $ &
   优先级为:@ > # > $ > &
   
   X@Y = (X+1)*(Y+2)
   X#Y = (2X+3)*(3Y+4)
   X$Y = (3X+11)*(2Y+7)
   X&Y = (5X+20)*(4Y+1)
   
   X#Y@Z = X#(Y@Z)
   
   编写火星计算器程序,计算火星文表达式;
   
   例子:
   输入:1@2

   输出:8 

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

int changeOp(char op)
{
	switch (op)
	{
	case '&':return 1;
	case '$':return 2;
	case '#':return 3;
	case '@':return 4;
	}
	return 0;
}

int cal(int num1, int num2, int op)
{
	switch(op)
	{
	case 1:return (5*num1+20)*(4*num2+1);
	case 2:return (3*num1+11)*(2*num2+7);
	case 3:return (2*num1+3)*(3*num2+4);
	case 4:return (num1+1)*(num2+2);
	}
	return 0;
}

int main()
{
	string str;
	cin>>str;
	stack<int> numStack;
	stack<int> opStack;
	int num=0;
	char op;
	for (unsigned i=0;i<str.size();i++)
	{
		if (str[i]>='0'&&str[i]<='9')
			num=num*10+str[i]-'0';
		else
		{
			op=str[i];
			numStack.push(num);
			num=0;
			if (numStack.size()==1)
			{
				opStack.push(changeOp(op));
				continue;
			}
			int curOp=changeOp(op);
			int prevOp=opStack.top();
			if(prevOp>=curOp)
			{
				int num1=numStack.top();
				numStack.pop();
				int num2=numStack.top();
				numStack.pop();
				numStack.push(cal(num1,num2,prevOp));
				opStack.pop();
				opStack.push(curOp);
			}
			else
			{
				opStack.push(curOp);
			}
		}
	}
	numStack.push(num);
	while (!opStack.empty())
	{
		int num1=numStack.top();
		numStack.pop();
		int num2=numStack.top();
		numStack.pop();
		numStack.push(cal(num2,num1,opStack.top()));
		opStack.pop();
	}
	cout<<numStack.top()<<endl;
	system("pause");
	return 0;
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值