# Add, subtract, multiply and divide -- counting garlic guests (Blue Bridge Cup)

Here's the subject

Two points should be noted:

1. For the convenience of calculation, I add the left bracket at the beginning and the right bracket at the end of the input expression

2. The power operation is set to the lowest priority. (because this will make the priority of the next operator must be ≥ the power operator) this will output the result correctly.

The code is as follows:

```#include <iostream>
#include <stdlib.h>
#include <stack>
#include <map>
#include <math.h>
#define ll long long
using namespace std;
stack <ll> num;
stack <char> ch;
int yunsuan()
{
ll x2=num.top();            //Note the order of x1 and x2
num.pop();
ll x1=num.top();
num.pop();
char c=ch.top();
ch.pop();
switch(c)
{
case '+':
return x1+x2;
break;
case '-':
return x1-x2;
break;
case '*':
return x1*x2;
break;
case '/':
return x1/x2;
break;
case '^':
return x1 = pow(x1,x2);
break;
}
return 0;
}
bool cmp(char top,char a)
{

if((top=='('))
return false;
if(a=='^')
return false;
if((top=='+'||top=='-') && (a=='*'||a=='/'))
return false;
if((a=='+'||a=='-'))
return true;
return true;
}
int main()
{

string s;
cin>>s;
s = s+")";
ch.push('(');
int len = s.length();
for(int i=0; i<len; i++)
{
if(s[i]>='0' && s[i]<='9')
{
ll a=s[i]-'0';
for(i=i+1; i<len; i++){
if(s[i]>='0' && s[i]<='9')
{
a=a*10+(s[i]-'0');
}
else
{
i--;
break;
}
}
num.push(a);
}
else         //When it's a symbol
{
while(cmp(ch.top(),s[i]))
{
ll a = yunsuan();
num.push(a);
}
ch.push(s[i]);
}
}
cout<<num.top();
return 0;
}
```

If there is a better solution or want to discuss the place welcome to leave a message!

Posted on Fri, 31 Jan 2020 20:42:16 -0500 by loveranger