表达式求值

https://www.acwing.com/problem/content/3305/

input:
(2+2)*(1+1)

output:
8

#include<unordered_map>
const int N = 1e5 + 50;

stack<int>num;
stack<char>op;
char s[N]; 

void eval(){
	int b = num.top();
	num.pop();
	int a = num.top();
	num.pop();
	char c = op.top();
	op.pop();
	int x = 0;
	if(c == ‘+‘)x=a+b;
	else if(c == ‘-‘)x=a-b;
	else if(c == ‘*‘)x=a*b;
	else if(c == ‘/‘)x=a/b;
	num.push(x);
}

void work(){
	unordered_map<char,int>pr{{‘+‘,1},{‘-‘,1},{‘*‘,2},{‘/‘,2}};
	scanf("%s",s);
	int lena = strlen(s);
	for(int i=0;i<lena;i++){
		char c = s[i];
		if(isdigit(c)){
			int x=0,j=i;
			while(j<lena&&isdigit(s[j])){
				x=x*10+(s[j]-‘0‘);
				j++;
			}
			i=j-1;
			num.push(x);
		}
		else if(c == ‘(‘)op.push(c);
		else if(c == ‘)‘){
			while(op.top() != ‘(‘)eval();
			op.pop();
		}
		else {
			while(op.size() && pr[op.top()] >= pr[c])eval();
			op.push(c);
		} 
	}
	while(op.size())eval();
	printf("%d\n",num.top());
}

表达式求值

上一篇:Wave 文件(11): 使用 waveIn...函数录制 wav 文件


下一篇:SonarQube+jenkins实现CodeReview环境搭建