#include
#include
#include
const int N = 66;
char s[N], stkc[N];
int stki[N], tpi, tpc, x;
inline int prev(char c) {
switch(c) {
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
case '(': return -1;
case ')': return 0;
}
return 0;
}
int main() {
scanf("%s", s+1);
s[0] = '(', s[strlen(s)-1] = ')';
for (int i = 0; s[i]; ++i) {
if ((s[i]=='-'&&s[i-1]=='(') || (s[i]>='0'&&s[i]<='9')) {
bool neg = false;
if (s[i] == '-') neg = true, ++i;
int ans = s[i++] - '0';
while (s[i]>='0' && s[i]<='9')
ans = 10*ans + s[i++]-'0';
if (neg) ans = -ans;
stki[++tpi] = ans;
}//i此时已经不是数字,所以可以继续判断运算符
if (s[i] == '(') {
stkc[++tpc] = '(', ++x;
} else {
//一个运算符前面不是数字或右括号,报错
if ((s[i-1]<'0' || s[i-1]>'9') && s[i-1]!=')') {
puts("NO");
return 0;
}
while (tpc && prev(s[i])<=prev(stkc[tpc])) {
char op = stkc[tpc--];
int b = stki[tpi--], a = stki[tpi--];
if (op == '+') a += b;
else if (op == '-') a -= b;
else if (op == '*') a *= b;
else if (op == '/') a /= b;
else if (op == '^') a = pow(a, b);
stki[++tpi] = a;
}
if (s[i] == ')') {
//括号匹配不对,报错
if (!x) { puts("NO"); return 0; }
--tpc, --x;
continue;
}
stkc[++tpc] = s[i];
}
}
if (x) puts("NO");//有多余括号,报错
else printf("%d", stki[tpi]);
return 0;
}
转载请注明来源