算术字符串计算(中缀-后缀转换 后缀计算)

笔试时候遇到了两次,给一个字符串“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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值