题目链接:https://leetcode-cn.com/problems/calculator-lcci/
题目如下:
class Solution {
public:
int calculate(string s) {
stack<int> stk1;//存放数字
stack<char> stk2;//存放运算符
long long sum=0;//计算运算符之前的数
bool flag=false;//以防数字为0的情形,如0+0
for(auto e:s){
if(isdigit(e)) {//判断是否为为数字
sum=sum*10+e-'0';
flag=true;
}else if(e==' ') {
continue;
}else {//为运算符
stk1.push(sum);sum=0;flag=false;//数字入栈
if(stk2.size()==0) stk2.push(e);//判断是否已存有运算符
else {
if(judge_priority(e,stk2.top())>0){stk2.push(e);continue;}
while(stk2.size()!=0&&judge_priority(e,stk2.top())<=0){//注:同级运算符计算,只能从左往右,不能从右往左
int a,b;
a=stk1.top();stk1.pop();
b=stk1.top();stk1.pop();cout<<a<<','<<b<<endl;
char ch=stk2.top();stk2.pop();
stk1.push(cal(a,b,ch));
}
stk2.push(e);
}
}
}
if(stk2.size()==0) return sum;
if(flag==true) stk1.push(sum);//放入最后一个数
//最后的栈中内容计算
while(stk2.size()!=0){
int a,b;
a=stk1.top();stk1.pop();
b=stk1.top();stk1.pop();
char e=stk2.top();stk2.pop();
stk1.push(cal(a,b,e));
}
return stk1.top();
}
int judge_priority(char a,char b){
if((a=='*'||a=='/')&&(b=='+'||b=='-')) return 1;//当前运算符比栈顶运算符大
else if((b=='*'||b=='/')&&(a=='+'||a=='-')) return -1;//当前运算符比栈顶运算符号小
else return 0;
}
int cal(int a,int b,char op){
switch(op){
case '*':return b*a;
case '/':return b/a;
case '+':return b+a;
case '-':return b-a;
}
return 0;
}
};