当前位置:   article > 正文

华为校招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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/919091
推荐阅读
相关标签
  

闽ICP备14008679号