中缀表达式直接计算
计算器
class Solution {
private:
stack<char> opt;
stack<long> nums;
public:
bool isOperator(char op){
return (op=='+')|| (op=='*') || (op=='/') ||op==('-')||(op=='(')||(op==')');
}
//栈内优先级
int isp(char ch)
{
switch (ch)
{
case '#': return 0;
case '(': return 1;
case '^':return 7;
case '*':case '/':case '%':return 5;
case '+':case '-':return 3;
case ')':return 8;
default : return 0;
}
}
//栈外优先级
int icp(char ch)
{
switch (ch)
{
case '#': return 0;
case '(': return 8;
case '^':return 6;
case '*':case '/':case '%':return 4;
case '+':case '-':return 2;
case ')':return 1;
default : return 0;
}
}
int calculate(string s) {
int ans = 0;
int i = 0;
while(i<s.length()||!opt.empty()){
if(i<s.length()){
if(s[i]==' '){
i++;
continue;
}
if(isOperator(s[i])){
if(opt.empty()||icp(s[i])>isp(opt.top())){
opt.push(s[i]);
i++;
}else{
long b = nums.top();
nums.pop();
long a = nums.top();
nums.pop();
switch(opt.top()){
case '+': a+=b;break;
case '-': a-=b;break;
case '*': a*=b;break;
case '/': a/=b;break;
default:break;
}
opt.pop();
nums.push(a);
}
}else{
long num = 0;
while (i < s.length() && s[i] >= '0' && s[i] <= '9') {
num = num * 10 + s[i] - '0';
i++;
}
nums.push(num);
}
}else{
while(!opt.empty()){
char op = opt.top();
opt.pop();
long b = nums.top();
nums.pop();
long a = nums.top();
nums.pop();
switch(op){
case '+': a+=b;break;
case '-': a-=b;break;
case '*': a*=b;break;
case '/': a/=b;break;
default:break;
}
nums.push(a);
}
}
}
ans = nums.top();
return ans;
}
};