表达式求值/华为机试(C/C++)

题目描述

给定一个字符串描述的算术表达式,计算出结果值。

输入字符串长度不超过100,合法的字符包括”+, -, *, /, (, )”,”0-9”,字符串内容的合法性及表达式语法的合法性由做题者检查。本题目只涉及整型计算。

输入描述:

输入算术表达式

输出描述:

计算出结果值

示例1

输入

400+5

输出

405

代码:

//第五十二题  表达式求值
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int main()
{
	string s;
	while (cin >> s)
	{
		stack<char> opera;
		vector<int> numcnt;
		string s1;//后缀表达式
				  //中缀表达式转后缀表达式
		for (int i = 0; i<s.size(); i++)
		{
			if (s[i] >= '0'&&s[i] <= '9')
			{
				int tmp = 0;
				while (s[i] >= '0'&&s[i] <= '9')
				{
					tmp++;
					s1 += s[i];
					i++;
				}
				i--;
				numcnt.push_back(tmp);
			}
			else if (s[i] == '-' || s[i] == '+')
			{
				if (s[i] == '-' && (s[i - 1] == '(' ))
					s1 += '0';
				while (!opera.empty() && (opera.top() == '*' || opera.top() == '/' || opera.top() == '+' || opera.top() == '-'))
				{
					s1 += opera.top();
					opera.pop();
				}
				opera.push(s[i]);
			}
			else if (s[i] == '*' || s[i] == '/')
			{
				while (!opera.empty() && (opera.top() == '*' || opera.top() == '/'))
				{
					s1 += opera.top();
					opera.pop();
				}
				opera.push(s[i]);
			}
			else if (s[i] == '(' )
				opera.push(s[i]);
			else if (s[i] == ')')
			{
				while (opera.top() != '(')
				{
					s1 += opera.top();
					opera.pop();
				}
				opera.pop();
			}
			else
				cout << "Invalid input!" << endl;
		}
		while (!opera.empty())
		{
			s1 += opera.top();
			opera.pop();
		}
		//计算后缀表达式的值
		stack<int> nums;
		int ind = 0;
		for (int i = 0; i<s1.size(); i++)
		{
			if (s1[i] >= '0'&&s1[i] <= '9')
			{
				int total = 0;
				while (numcnt[ind]--)
					total = 10 * total + (s1[i++] - '0');
				i--;
				nums.push(total);
				ind++;
			}
			else
			{
				int tmp1 = nums.top();
				nums.pop();
				int tmp2 = nums.top();
				nums.pop();
				if (s1[i] == '+')
					nums.push(tmp2 + tmp1);
				else if (s1[i] == '-')
					nums.push(tmp2 - tmp1);
				else if (s1[i] == '*')
					nums.push(tmp2*tmp1);
				else
					nums.push(tmp2 / tmp1);
			}
		}
		cout << nums.top() << endl;
	}
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值