整数求值(华为上机)

整数算术表达式求值
描述:
求由+-*/()组成的整数算术表达式的值。如1+2*3=7,(1+2)*3=9。除法运算,除不尽时向下取整,如(1+2)/2+1=2。不考虑数值溢出。不考虑除数为0。不考虑括号嵌套。
运行时间限制: 10 Sec
内存限制: 128 MByte
输入:
一行字符串,长度小于128个字节
输出:
计算结果,整数
样例输入:
1+3+4+5
样例输出:

13

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

bool compare(char a,char b)//a>=b,return 1;
{
	if(a=='*'||a=='/')
		return true;
	else
	{
		if(b=='+'||b=='-')
			return true;
		else
			return false;
	}
		
	
}

int main()	
{

	char opera;
	int num;
	vector<int> input;
	stack<char> s;
	while((opera=cin.get())!='\n')
	{
		if(opera=='+'||opera=='-'||opera=='*'||opera=='/')
		{
			while(!s.empty()&&s.top()!='('&&compare(s.top(),opera))
			{
				input.push_back(s.top()-'0');
				s.pop();
			}
			s.push(opera);
		}
		else if(opera=='('||opera==')')
		{
			if(opera=='(')
				s.push(opera);
			else
			{
				while(s.top()!='(')
				{
					input.push_back(s.top()-'0');
					s.pop();
				}
				s.pop();

			}
		}
		else
		{
			cin.unget();
			cin>>num;
			input.push_back(num);
		}
	}


	while(!s.empty())
	{
		input.push_back(s.top()-'0');
		s.pop();
	}
	
	stack<int> out;
	for(int i=0;i<input.size();i++)
	{
		char op=input[i]+'0';
		if(op=='+'||op=='-'||op=='*'||op=='/')
		{
			int second=out.top();
			out.pop();
			int first=out.top();
			out.pop();
			int result=0;
			if(op=='+')
				result=first+second;
			else if(op=='-')
				result=first-second;
			else if(op=='*')
				result=first*second;
			else if(op=='/')
				result=first/second+1;
			out.push(result);


		}
		else
		{
			out.push(input[i]);
		}
	}
	cout<<out.top()<<endl;
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值