火星计算器:
火星人使用运算符:@ # $ &
优先级为:@ > # > $ > &
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
火星人使用运算符:@ # $ &
优先级为:@ > # > $ > &
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;
}