算法训练 表达式计算

题目链接

问题描述

  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。

分析:简单的四则运算用两个stack,opt记录符号栈,num记录数字。每次加入符号,如果栈不为空&&栈顶元素优先级>=加入的符号优先级时,进行运算。如果带有括号,则可以递归进行四则运算(当成一个新的没有括号的四则运算)。

优化,在最后结尾加入一个‘)’,这样每次最后结束是能直接清空之前的符号栈完成计算,减少重复代码。

#include <iostream>
#include <stack>
#include <map>
#include <cctype>
using namespace std; 
map<char, int> m;
string s;
 
int compute(int a,int b,char c){
	if( c == '+')  return a+b;
	else if( c == '-')  return b-a;
	else if( c == '*')  return a*b;
	else  return b/a;
}
 
int getInt(int &i){
	int n = 0;
	for(; isdigit(s[i]) && i < s.length(); i++) //都是int,没有小数点
		n = n*10 + s[i]-'0';
	i--;
	return n;
}
 
int calculate(int &i){
	stack<char> opt;
	stack<int> num;
	if(s[i] == '-'){// 防止出现开头负数的情况。
		num.push( -getInt(++i));
		i++;		
	}	
	for( ; i < s.length(); i++){		
		if(isdigit(s[i])){
			num.push( getInt(i));
		}else{
			if(s[i] == '('){
				num.push( calculate(++i)); //递归计算括号内的式子										
			} else {
				char c;
				while( !opt.empty() && m[c = opt.top()] >= m[s[i]]){					
					int a = num.top(); num.pop();
					int b = num.top(); num.pop();
					num.push( compute(a, b, c));
					opt.pop();
				}
				if(s[i] == ')') break;
				opt.push(s[i]);
			}
		}
	}
	return num.top();
}
 
int main(int argc, char** argv) {
	m['+'] = m['-'] = 1;
	m['*'] = m['/'] = 2;
	m[')'] = 0;	 
	cin>> s;
	s.append(1,')'); // 最后添加')'便于减少代码量 
	int i = 0;
	cout<< calculate(i) << "\n";
	return 0;
}

输入格式

  输入一行,包含一个表达式。

输出格式

  输出这个表达式的值。

样例输入

1-2+3*(4-5)

样例输出

-4

数据规模和约定

  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值