51-表达式计算(带括号的)

            算法训练 表达式计算  
时间限制:1.0s   内存限制:256.0MB
    
问题描述
  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
  输入一行,包含一个表达式。
输出格式
  输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;

int bijiao(char x){
	switch(x){
		case '+': return 1;
		case '-': return 1;
		case '*': return 2;
		case '/': return 2;
		case '(': return -1;
		case '#': return 0;
	}
	return 0;
}

int f(string str){
	int ans = 0;
	stack <char> cst;
	stack <int> ist;
	str += '#';
	cst.push('#');
	int i = 0, len = str.length();
	while(i < len){
		if(str[i] >= '0' && str[i] <= '9'){
			int sum = 0;
			while(str[i] >= '0' && str[i] <= '9'){
				sum = sum * 10 + (str[i] - '0');
				i++;
			}
			if(cst.top() == '-'){  //将减号换为加一个负数 
				cst.pop();
				cst.push('+');
				sum = -sum;
			}
			ist.push(sum);
		}
		if(str[i] == '('){
			cst.push(str[i]);
			i++;
		}
		else if(str[i] == ')'){
			while(cst.top() != '('){ //一直碰到左括号结束 
				char ch;
				ch = cst.top();
				cst.pop();
				int a = ist.top();
				ist.pop();
				int b = ist.top();
				ist.pop();
				int x = 0;
				if(ch == '+'){
					x = b + a;
				}
				else if(ch == '-'){
					x = b - a;
				}
				else if(ch == '*'){
					x = b * a;
				}
				else if(ch == '/'){
					x = b / a;
				}
				ist.push(x);
//				i++;
			}
			cst.pop();
			i++;
		}
		else if(bijiao(str[i]) >= bijiao(cst.top())){ //优先级高的直接入栈 
			cst.push(str[i]);
			i++;
		}
		else if(bijiao(str[i]) < bijiao(cst.top())){
			while(bijiao(str[i]) < bijiao(cst.top())){ //直到当前的符号优先级比栈顶优先级高,才入栈,否则一直运算 
				char ch;
				ch = cst.top();
				cst.pop();
				int a = ist.top();
				ist.pop();
				int b = ist.top();
				ist.pop();
				int x = 0;
				if(ch == '+'){
					x = b + a;
				}
				else if(ch == '-'){
					x = b - a;
				}
				else if(ch == '*'){
					x = b * a;
				}
				else if(ch == '/'){
					x = b / a;
				}
				ist.push(x);
			}
			cst.push(str[i]);
			i++;
		}
	}
	return ist.top();
}

int main(){
	string str;
	cin >> str;
	cout << f(str) << endl;
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8456004.html