问题描述
输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
分析:简单的四则运算用两个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内进行。