The bracket sequence, the calculation of the expression is almost inseparable from the stack. For the calculation of the expression, we can use two stacks to store numbers and characters respectively, and then solve
Rules: When traversing to an operator, compare the priority of the current operator and the operator on the top of the stack. As long as the priority of the top of the stack is greater than or equal to the current priority, then the previous formula can be calculated. See the code for details.
Code
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>#include<stack>usingnamespace std;
stack<int> nums;
stack<char> opt;intqmi(int m,int k){
int res =1;while(k){
if(k &1) res = res * m;
m = m * m;
k >>=1;}return res;}voidcal(){
int a = nums.top();
nums.pop();int b = nums.top();
nums.pop();char c = opt.top();
opt.pop();int res;if(c =='+') res = b + a;if(c =='-') res = b - a;if(c =='*') res = b * a;if(c =='/') res = b / a;if(c =='^') res =qmi(b, a);
nums.push(res);}intmain(){
string str;
cin >> str;if(str[0]=='-') str ='0'+ str;//将式子转化规范//出现多余括号处理
string left;for(int i =0; i < str.size(); i++) left +='(';
str = left + str +')';for(int i =0; i < str.size(); i++){
if(str[i]>='0'&& str[i]<='9'){
int j = i, t =0;while(str[j]>='0'&& str[j]<='9'){
t = t *10+ str[j]-'0';
j++;}
nums.push(t);
i = j -1;}else{
char c = str[i];if(c =='(') opt.push(c);elseif(c =='+'|| c =='-'){
//'-' 是负号的情况if(c =='-'&&!(str[i -1]>='0'&& str[i -1]<='9')&& str[i -1]!=')'){
// 将-(...)变成-1 * (...)if(str[i +1]=='('){
nums.push(-1);
opt.push('*');}else{
int j = i +1, t =0;while(str[j]>='0'&& str[j]<='9'){
t = t *10+ str[j]-'0';
j++;}
nums.push(-t);
i = j -1;}}else{
// '-'是减号的情况while(opt.top()!='(')cal();
opt.push(c);}}elseif(c =='*'|| c =='/'){
while(opt.top()=='*'|| opt.top()=='/'|| opt.top()=='^')cal();
opt.push(c);}elseif(c =='^'){
while(opt.top()=='^')cal();
opt.push(c);}elseif(c ==')'){
while(opt.top()!='(')cal();
opt.pop();}}}
cout << nums.top()<< endl;return0;}