通过找寻最低优先级的运算符来进行递归,由递归栈的性质可以得到先找最低优先级的然后递归就可以顺利将最后也就是最高优先级的运算符先计算然后计算结果返回到上一层接着计算。
在中间还牵扯到多余括号的处理以及字符串数字转数字。
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
string s;
//字符串转化成数字
ll string_to_ll(int l, int r) {
ll ans = 0;
for (;l<=r;l++) {
ans = ans*10+(s[l]-'0');
}
return ans;
}
ll calc(int l, int r) {
int pos1=-1, pos2=-1, pos3=-1;
int num = 0;
for (int i=l;i<=r;i++) {
if (s[i]=='(') num++;
if (s[i]==')') num--;
if (num<=0) {
if (s[i]=='-'||s[i]=='+') pos1 = i;
if (s[i]=='*'||s[i]=='/') pos2 = i;
if (s[i]=='^') pos3 = i;
}
}
//如果三个都没找到证明在最外面包的有括号
if (pos1==-1&&pos2==-1&&pos3==-1) {
//证明在左边外层有多余的括号
if (num>0) {
return calc(l+1, r);
}
if (num==0&&s[l]=='(')
return calc(l+1, r-1);
if (num<0&&s[l]==')')
return calc(l, r+1);
return string_to_ll(l, r);
}
if (pos1!=-1) {
if (s[pos1]=='+')
return calc(l, pos1-1)+calc(pos1+1, r);
if (s[pos1]=='-')
return calc(l, pos1-1)-calc(pos1+1, r);
} else if (pos2!=-1) {
if (s[pos2]=='*')
return calc(l, pos2-1)*calc(pos2+1, r);
if (s[pos2]=='/')
return calc(l, pos2-1)/calc(pos2+1, r);
} else if (pos3!=-1) {
return pow(calc(l, pos3-1),calc(pos3+1, r));
}
return 0;
}
int main() {
cin>>s;
cout<<calc(0, s.size()-1);
return 0;
}

京公网安备 11010502036488号