【参考代码】
#include<bits/stdc++.h>
using namespace std;
#define N 1005
int pri[128];
void initPri()
{
pri['('] = 5;
pri['^'] = 4;
pri['*'] = pri['/'] = 3;
pri['+'] = pri['-'] = 2;
pri[')'] = 1;
}
int calc(int a, int b, char c)
{
switch(c)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return (int)pow(a,b);
}
}
int main()
{
initPri();
int n, num = 0;
char s[N];
cin >> s;
int len = strlen(s);
s[len] = ')';
stack<int> nStk;
stack<char> cStk;
bool isFormingNum = false;
for(int i = 0; i <= len; ++i)
{
if(s[i] >= '0' && s[i] <= '9')
{
isFormingNum = true;
num = num * 10 + s[i] - '0';
}
else
{
if(isFormingNum)
{
nStk.push(num);
num = 0;
isFormingNum = false;
}
while(!(cStk.empty() || pri[s[i]] > pri[cStk.top()] || cStk.top() == '('))
{
int b = nStk.top(); nStk.pop();
int a = nStk.top(); nStk.pop();
char c = cStk.top(); cStk.pop();
nStk.push(calc(a, b, c));
}
if(cStk.empty() == false && cStk.top() == '(' && s[i] == ')')
cStk.pop();
else
cStk.push(s[i]);
}
}
cout << nStk.top();
return 0;
}