笔试时候遇到了两次,给一个字符串“3*4+5*6-2”这样的字符串,让你编写程序计算它的值。今天写了一下,可以实现,带有括号的也行。
#include <iostream>
#include <stack>
#include <vector>
#include <stdio.h>
#include <string>
using namespace std;
void mid2last(char *str,char *res,int len)
{
char *temp=res;
stack<char> st;
for(int i=0;i<len;i++)
{
if(str[i]==')'&&!st.empty())
{
*temp++=st.top();
st.pop();
}
if(str[i]=='+'||str[i]=='-')
{
if(st.top()=='(')
{
st.pop();
st.push(str[i]);
continue;
}
while(!st.empty())
{
*temp++=st.top();
st.pop();
}
st.push(str[i]);
}
if(str[i]>='0'&&str[i]<='9')
*temp++=str[i];
if(str[i]=='*'||str[i]=='\\')
{
if(!st.empty()&&(st.top()=='*'||st.top()=='\\'))
{
while(!st.empty())
{
*temp++=st.top();
st.pop();
}
st.push(str[i]);
}
else
st.push(str[i]);
}
if(str[i]=='(')
{
st.push(str[i]);
}
}
while(!st.empty())
{
*temp++=st.top();
st.pop();
}
}
int compute(char *str)
{
int res=0;
stack<int> stin;
while(*str!=NULL)
{
if(*str>='0'&&*str<='9')
stin.push(*str-'0');
if(*str=='+')
{
int a=stin.top();
stin.pop();
int b=stin.top();
stin.pop();
res=a+b;
stin.push(res);
}
if(*str=='*')
{
int a=stin.top();
stin.pop();
int b=stin.top();
stin.pop();
res=a*b;
stin.push(res);
}
if(*str=='-')
{
int a=stin.top();
stin.pop();
int b=stin.top();
stin.pop();
res=b-a;
stin.push(res);
}
if(*str=='\\')
{
int a=stin.top();
stin.pop();
int b=stin.top();
stin.pop();
res=b/a;
stin.push(res);
}
str++;
}
res=stin.top();
return res;
}
int main()
{
char str[]="3*4+5*(6-2)";
int len=strlen(str);
char *resLast=new char[len+1];
mid2last(str,resLast,len+1);
char *res=resLast;
while(*res>0)
cout<<*(res++)<<" ";
cout<<endl;
int result=0;
result=compute(resLast);
cout<<"the answer is "<<result<<" "<<endl;
}