STL 栈:计算(calc)

9 篇文章 1 订阅
4 篇文章 0 订阅

小明在你的帮助下,破密了 Ferrari 设的密码门,正要往前走,突然又出现了一个密码

门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是

密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)

输入

输入 1 行,为一个算式。

输出

输出 1行,就是密码。

样例

输入

1+(3+2)*(7^2+6*9)/(2)

输出

258

提示

【限制】

100%的数据满足:算式长度<=30 其中所有数据在 2^31-1 的范围内。

[参考代码]

#include<bits/stdc++.h>
using namespace std;
char str[10000];
int n;
stack<int>s1;//数字
stack<char>s2;//运算符
void calc() {
	int y=s1.top();
	s1.pop();
	int x=s1.top();
	s1.pop();
	char z=s2.top();
	s2.pop();
	if(z=='+')
		s1.push(x+y);
	else if(z=='-')
		s1.push(x-y);
	else if(z=='*')
		s1.push(x*y);
	else if(z=='/' )
		s1.push(x/y);
	else
		s1.push(pow(x,y));
}
int level(char x) { //运算等级
	if(x=='+'||x=='-')
		return 1;
	if(x=='*'||x=='/')
		return 2;
	if(x=='^')
		return 3;
	return 0;
}
int main() {
	scanf("%s",str+1);
	n=strlen(str+1);//有效符号个数
	//连续运算符
	for(int i=1; i<=n; i++) {
		if(str[i]!='('&&str[i]!=')'&&(str[i]<'0'||str[i]>'9')&&str[i+1]!='('&&str[i+1]!=')'&&(str[i+1]<'0'||str[i+1]>'9')&&i!=n) {
			cout<<"NO";
			return 0;
		}
		if(str[i]=='('&&(str[i+1]=='+'||str[i+1]=='*'||str[i+1]=='/'||str[i+1]=='^')) {
			cout<<"NO";
			return 0;
		}
	}
	//开头特判
	bool tepan=false;
	if(str[1]=='-')
		tepan=true;
	else if(str[2]=='-'&&str[1]=='(')
		tepan=true;
	//初始化
	int temp=0;
	bool flag=false;
	//核心部分
	for(int i=1; i<=n; i++) {
		if(str[i]>='0'&&str[i]<='9') {
			temp=temp*10+str[i]-48;
			flag=true;
		} else {
			if(flag==true) {
				if(tepan==true)
					s1.push(-temp);
				else
					s1.push(temp);
				temp=0;
				flag=false;
				tepan=false;
			}
			if(str[i]=='(') {
				s2.push(str[i]);
				//符号特判
				if(str[i+1]=='-')
					tepan=true;
				continue;
			} else if(str[i]==')') {
				while(s2.top()!='(')
					calc();
				s2.pop();
				continue;
			}
			while(s2.empty()==false&&level(s2.top())>=level(str[i]))
				calc();
			if((str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'||str[i]=='^')&&tepan==false)
				s2.push(str[i]);
		}
	}
	if(flag==true) {
		s1.push(temp);
		temp=0;
		flag=false;
	}
	while(s2.empty()==false)
		calc();
	if(s2.empty()==false||s1.size()>1) {
		cout<<"NO";
		return 0;
	}
	cout<<s1.top();
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值