洛谷P1981表达式求值(模拟)

最近写模拟写的挺多的,甚至用模拟写了一个java计算器。。

这个题目意思很明确了:

直接模拟。把输入进来的中缀表达式转换为后缀表达式,然后根据求后缀表达式的方法求解即可。

#include <bits/stdc++.h>
using namespace std;
string str;
stack<string> st;
vector<string> v;
const int mode=10000;

bool isdigital(char s){
	return (s>='0' && s<='9');
}

void init(string s,int len){//中缀表达式转后缀表达式 
	string temp = "";
	for (int i=0;i<len;i++){
		if(!isdigital(s[i])){
			v.push_back(temp);
			temp="";
			string t = "a";
			t[0]=s[i];
			if(st.size() == 0){
				st.push(t);
			}
			else{
				if(s[i] == '*'){//当前是乘号,则只需要看栈中的首元素是否为乘号 
					while(!st.empty()){
						string cur=st.top();
						if(cur.compare("*") == 0){
							v.push_back(cur);
							st.pop();
						}
						else break;
					}
					st.push(t);		
				}
				else{
					while(!st.empty()){//当前是加号,无论栈中是什么元素都要压入vector(因为栈中的元素的优先级大于或等于加号) 
						string cur=st.top();
						v.push_back(cur);
						st.pop();
					}
					st.push(t);			
				}
			}
		}
		else {
			temp+=s[i];
		}
	}
	v.push_back(temp);//加一次最后的数字 
	
	while(!st.empty()){//把储存运算符的栈中的所有元素按顺序压入vector 
		string cur=st.top();
		v.push_back(cur);
		st.pop();
	}
}

int change(string s){//把字符串变成一个数字 
	int f=1;
	int ans=0;
	for (int i=s.length()-1;i>=0;i--){
		ans+=f*(s[i]-'0');
		f*=10;
	}
	return ans;
}

stack <int> ss;
void solve(){//后缀表达式求解 
	for (int i=0;i<v.size();i++){
		string cur=v[i];
		if(isdigit(cur[0])){
			int t=change(cur) % mode;//取模 
			ss.push(t);
		}
		else{
			int a=ss.top();
			ss.pop();
			int b=ss.top();
			ss.pop();
			int t;
			if(cur[0]=='*') t= (b %mode)* (a%mode);//取模 
			else t=(b % mode + a % mode) % mode;
			ss.push(t);
		}
	}
}

int main(){
	cin>>str;
	int len=str.length();
	init(str,len);
	solve();
	printf("%d\n",ss.top());//输出栈顶元素即为答案 
	return 0;
}

延伸:此处对代码进行适当的修改还可以实现根号,阶乘,幂积,带括号的运算等等,只需要把每个运算符的优先级确定便可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值