实现个位数的运算
//中序表达式转换后缀表达式:-与+为同一优先级但是要满足左向右的执行顺序,处理时要弹出先进栈,压进后遇到的,*与/同样,
//*/遇到-+时要要弹出把-+压进栈,同时要考虑到-||+ *这种情况:处理是*弹出栈如果满足剩下大小>=1再与- +判断
//计算后续表达式时数据压栈要注意字符转换为数字,计算结果转换为字符再进栈。
#include<iostream>
#include <stack>
#include <vector>
using namespace std;
int calculate2(int len1,vector<char>vc)
{
stack<char>sc;
for (int m=0;m<len1;m++)
{
//cout<<vc[m];
if (vc[m]>'0')
{
sc.push(vc[m]);
}
else
{
int a=sc.top()-'0';
sc.pop();
int b=sc.top()-'0';
sc.pop();
int c;
switch (vc[m])
{
case '*':
c=a*b;
break;
case '/':
c=b/a;
break;
case '+':
c=a+b;
break;
case '-':
c=b-a;
break;
}
c+=(int)'0';
char f=(char)c;
sc.push(f);
}
}
int sum=sc.top()-'0';
return sum;
}
int calculate(int len,char*expStr)
{
stack<char>ss;
vector<char>vs;
static int flag=0;
for (int i=0;i<len;i++)
{
if (expStr[i]<'0')
{
if (flag!=0)
{
if (ss.top()!='/'&&ss.top()!='*')
{
if (expStr[i]=='*'||expStr[i]=='/')
{
ss.push(expStr[i]);
}
else
{
vs.push_back(ss.top());
ss.pop();
ss.push(expStr[i]);
}
}
else
{
if (ss.top()==expStr[i])
{
vs.push_back(expStr[i]);
}
else
{
if (expStr[i]=='-'||expStr[i]=='+')
{
vs.push_back(ss.top());
ss.pop();
int size=ss.size();
if (size>=1)//重要“=”
{
if (ss.top()=='-'||ss.top()=='+')
{
vs.push_back(ss.top());
ss.pop();
ss.push(expStr[i]);
}
}
else
{
ss.push(expStr[i]);
}
}
else
{
vs.push_back(ss.top());//有时候会忘记相同级别的运算处理
ss.pop();
ss.push(expStr[i]);
}
}
}
}
else
{
ss.push(expStr[i]);
flag=1;
}
}
else
{
vs.push_back(expStr[i]);
}
}
while(!ss.empty())
{
vs.push_back(ss.top());
ss.pop();
}
int sum3=calculate2(len,vs);
return sum3;
}
int main()
{
int len=13;
char*expStr="8/3*3-2*3*2+8";
int sum1=calculate(len,expStr);
cout<<sum1<<endl;
return 0;
}