返回题解分享
讨论 / 题解分享/ 帖子详情

算式求值 - 题解

#include <bits/stdc++.h>
#define objl '\n'
typedef long long ll;
using namespace std;
//数据结构在这里定义 
int mod = 10000;
stack<ll> num_st;//数字栈
stack<char> char_st;//符号栈 
string s;
//保存不同符号的优先级 
map<char, int> mp = {{'+',1},{'-',1},{'*',2},{'/',2}};

int solve(){
//cin cout在这里 
	cin >> s;
	//记录下一个数字的信息 
	ll tmp = 0;
	bool flag = false;
	for(int i = 0; i < s.size();i++){
		if(s[i] >= '0'&& s[i] <= '9'){
			tmp = tmp * 10 + s[i] - '0';
			flag = true;
		}else{//处理符号
			//先把符号前面的数字入栈 
			if(flag == true){
				num_st.push(tmp);
				tmp = 0;
				flag = false;
			} 
			//如果符号栈内还有符号,先把优先级大于本符号的先弹栈运算 
			while(!char_st.empty() && mp[s[i]] < mp[char_st.top()]){
				char c = char_st.top(); char_st.pop();
				//如果一个符号没有对应两个操作数表达式有误 
				if(num_st.size()<2) return -1;
				ll right = num_st.top(); num_st.pop();
				ll left = num_st.top(); num_st.pop();
				ll res;
				if(c=='+'){
					res = (left % mod + right % mod) % mod;
				}else if(c=='*'){
					res = (left % mod * right % mod) % mod;
				}
				num_st.push(res);
			}
			//处理完优先级更高的运算把本符号入栈
			char_st.push(s[i]); 
		}
	}
	//把最后一个数字入栈 
	if(flag == true) num_st.push(tmp);
	//处理符号栈剩余字符,从右往左计算同优先级的表达式 
	while(!char_st.empty()){
		char c = char_st.top(); char_st.pop();
		if(num_st.size()<2) return -1;
		ll right = num_st.top(); num_st.pop();
		ll left = num_st.top(); num_st.pop();
		ll res;
		if(c=='+'){
			res = (left % mod + right % mod) % mod;
		}else if(c=='*'){
			res = (left % mod * right % mod) % mod;
		}
		num_st.push(res);	
	} 
	//正确的表达式 符号栈为空 数字栈只剩下一个结果 
	if(num_st.size()==1&&char_st.empty()) return num_st.top() % mod;
	else return -1;
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t;//多组数据要cin
	//cin >> t;
	t = 1;
	while(t--){
		int res = solve();
		cout <<  res << endl;
	} 
	return 0;//必须加return 0 
}
0 回复 0 转发 0 喜欢 3 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!