算法训练 表达式计算
时间限制:1.0s 内存限制:256.0MB
问题描述
输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
输入一行,包含一个表达式。
输出格式
输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
表达式长度不超过100,表达式运算合法且运算过程都在int内进行。
解题思路:首先,题目所给的是中缀表达式,那么就要将中缀表达式变成后缀表达式;
步骤如下:
最后得到的后缀表达式就是:1 2 - 3 4 5 - * +;
然后按照符号开始就算: (1) -1 3 4 5 - * +
(2)-1 3 -1 * +
(3)-1 -3 +
(4)-4
如果扫描到的是数字,那么直接入数值栈;
如果是符号:
1):如果是‘(’,直接入符号栈
2):如果是‘)’,则把符号栈里的符号一次放入到数值栈,知道出现‘(’,然后将‘(’去掉
3):其它符号,如果前一个优先级比它低,则直接入符号栈,否则,将前一个符号入数值栈,并且在符号栈中移除,再将其入栈;
代码如下:
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
stack<string>s1,s2;
stack<int>q;
string s;
int f(string a)
{
int num=0;
for(int i=0;i<a.length();i++)
num = num*10 + a[i]-'0';
return num;
}
int main()
{
cin>>s;
s1.push("(");
string t="";
for(int i=0;i<s.length();i++)
{
if(s[i]>='0' && s[i]<='9'){
t+=s[i];
if(s[i+1]<'0' || s[i+1]>'9')
{s2.push(t); t="";}
} else{
string t1="";
t1=s[i];
if(s[i]=='(') s1.push(t1);
else if(s[i]==')'){
while(s1.top()!="("){
s2.push(s1.top());
s1.pop();
}
s1.pop();///去掉‘('
}else if( (s[i]=='+' || s[i]=='-') && (s1.top()!="(")){
s2.push(s1.top());
s1.pop();
s1.push(t1);
}else if( (s[i]=='*' || s[i]=='/') && (s1.top()=="*" || s1.top()=="/")){
s2.push(s1.top());
s1.pop();
s1.push(t1);
}else s1.push(t1);
}
}
while(!s1.empty()){///将符号全部入栈到数值栈
s2.push(s1.top());
s1.pop();
}
s2.pop();
while(!s2.empty()){///将栈中所有元素倒置
s1.push(s2.top());
///cout<<s2.top()<<endl;
s2.pop();
}
///cout<<endl;
int ans=0,a,b;
while(!s1.empty()){
if(s1.top()!="+" && s1.top()!="-" && s1.top()!="*" && s1.top()!="/"){
q.push(f(s1.top()));
}else {
b = q.top();
q.pop();
if(q.empty()) a=0;
else {a = q.top(); q.pop();}
if(s1.top() == "+") ans = a+b;
else if(s1.top() == "-") ans = a-b;
else if(s1.top() == "*") ans = a*b;
else ans = a/b;
///printf("%d %d %d\n",ans,a,b);
q.push(ans);
}
s1.pop();
}
///cout<<endl;
printf("%d\n",ans);
return 0;
}