求表达式的值

const int MAXN = 1e6 + 5;
int n,m;
bool f;
stack<int>st1;
stack<char>st2;

int qpw(int a,int b){
	int ans = 1;
	while(b){
		if(b & 1){
			ans*=a; 
		}
		a = a*a;
		b >>= 1; 
	}
	return ans;
}

int level(char x){  //返回优先级 
	if(x == '+' || x == '-')return 1;
	else if(x == '*' || x == '/')return 2;
	else if(x == '^')return 3;
	return 0;
} 

//弹出栈顶元素并计算 
void calc(stack<int>&st1,stack<char>&st2){
    int y = st1.top();st1.pop();
	int x = st1.top();st1.pop();
	char c = st2.top();st2.pop();
	
	if(c == '+')st1.push(x + y);
	else if(c == '-')st1.push(x-y);
	else if(c == '*')st1.push(x*y);
	else if(c == '/')st1.push(x/y);
	else if(c == '^')st1.push(qpw(x,y));
}
int c(int x){
	return x!=0;
}

char str[MAXN];
int sum[MAXN];

int main(){
	scanf("%s",str+1);
	n = strlen(str+1);
	for(int i=1;i<=n;i++){
		sum[i] += sum[i-1];
		if(str[i] == '(')sum[i] ++;
		if(str[i] == ')')sum[i] --;
	}
	f = true;
	for(int i=2;i<=n;i++){
		if(c(level(str[i])) && c(level(str[i-1]))){
			f = false;
			break;
		}
	}
	
	if((n ==1 && c(level(str[1]))) || sum[n] || !f){
		printf("NO\n");
		return 0;
	}
	f = false;
	int temp = 0;
	for(int i=1;i<=n;i++){
		//如果是数字 
		if(str[i] <='9' && str[i] >= '0'){
			temp = (temp << 3) + (temp << 1) + (str[i]- '0');
			f = true;
		}
		else{  //符号 
			if(f){  //先把数字放进去 
				st1.push(temp);
				temp = 0;
				f = 0;
			}
			if(str[i] == '('){
				st2.push(str[i]);
				continue;
			}
			if(str[i] == ')'){
				while(st2.top() != '(')calc(st1,st2);
				st2.pop();
				continue;
			}
			
			while(!st2.empty() && level(st2.top()) >= level(str[i]))
   			     calc(st1,st2);
			 st2.push(str[i]);
		} 
	}
	if(f){
		st1.push(temp);
		temp = 0;
		f = false;
	}
	while(st2.size()){
		calc(st1,st2);
	}
	printf("%d\n",st1.top());
	return 0;
}
 







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值