华为校招2019.8.7笔试第三题(栈+表达式求值)

输入一个表达式的字符串,只包含0、1、|、&、!、(、)七种字符,然后输出表达式的结果,保证输入合法。!优先级大于&大于|。
这题有个需要注意的点就是:!是一元运算符,这里考虑两种情况,如果!后面是数字,就直接进行运算,并将运算结果入栈。如果!后面是(,就将!压进符号栈,在(出栈时判断当前栈顶是否为!,若为!,将数字栈中的栈顶元素弹出进行!运算。

代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<vector>
#include<stack>
#include<sstream>
#include<unordered_map>
using namespace std;

stack<char>op;
stack<int>sn;
unordered_map<char, int>p_map;



int main() {
	p_map['('] = 0;
	p_map['|'] = 1;
	p_map['&'] = 2;
	string s;
	cin >> s;
	int len = s.length();


	for (int i = 0; i < len; i++) {
		if (s[i] == '0' || s[i] == '1') {
			int tmp = s[i] - '0';
			sn.push(tmp);
		}
		else if (s[i] == '!') {
			if (s[i + 1] == '0' || s[i + 1] == '1') {
				i++;
				int tmp = s[i] - '0';
				sn.push(!tmp);
			}
			else if (s[i + 1] == '(') {
				op.push(s[i]);
			}
		}
		else if (s[i] == '(') {
			op.push(s[i]);
		}
		else if (s[i] == ')') {
			while (op.top() != '(') {
				char c = op.top();
				op.pop();
				int n1 = sn.top();
				sn.pop();
				int n2 = sn.top();
				sn.pop();
				if (c == '|')
					sn.push(n1 | n2);
				else if (c == '&')
					sn.push(n1&n2);
			}
			op.pop();
			if (!op.empty() && op.top() == '!') {
				op.pop();
				int num = sn.top();
				sn.pop();
				sn.push(!num);
			}
		}
		else {
			if (!op.empty()) {
				while (!op.empty() && p_map[s[i]] < p_map[op.top()]) {
					char c = op.top();
					op.pop();
					int n1 = sn.top();
					sn.pop();
					int n2 = sn.top();
					sn.pop();
					if (c == '|') {
						sn.push(n1 | n2);
					}
					else if (c == '&') {
						sn.push(n1 & n2);
					}
				}
				op.push(s[i]);
			}
			else {
				op.push(s[i]);
			}
		}
	}
	while (!op.empty()) {
		char c = op.top();
		op.pop();
		int n1 = sn.top();
		sn.pop();
		int n2 = sn.top();
		sn.pop();
		if (c == '|')
			sn.push(n1 | n2);
		else if(c=='&')
			sn.push(n1 & n2);
	}
	cout << sn.top();

	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值