//参考老师代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<cmath>
#include<algorithm>
#define Maxn 100000
using namespace std;
int n,m;
stack<int> s1;
stack<char> s2;
inline int strlen_t(char t[])
{
int cnt=0;
for(int i=1;i<=Maxn;i++)
{
if(t[i]!='\0') ++cnt;
else break;
}
return cnt;
}
inline int lev(char x)
{
if(x=='+'||x=='-') return 1;
if(x=='*'||x=='/') return 2;
if(x=='^') return 3;
return 0;
}
inline void calculate(stack<int> &s1,stack<char> &s2)
{
int y=s1.top();s1.pop();
int x=s1.top();s1.pop();
char z=s2.top();s2.pop();
if(z=='+') s1.push(x+y);
if(z=='-') s1.push(x-y);
if(z=='*') s1.push(x*y);
if(z=='/') s1.push(x/y);
if(z=='^') s1.push((int)pow(x,y));
}
inline int c(int x)
{
return x!=0;
}
char str[Maxn];
int sum[Maxn];
int main()
{
scanf("%s",str+1);
// cout<<strlen_t(str)<<endl<<strlen_t(str+1)<<endl;
n=strlen_t(str);
// printf("%d\n",str[0]);
/* for(int i=0;i<=n;i++)
{
cout<<str[i];
}*/
int temp=0;
bool flag=false;
for(int i=1;i<=n;i++)
{
if('0'<=str[i]&&str[i]<='9')
{
temp=temp*10+str[i]-'0';
flag=true;
}
else
{
if(flag==true)
{
s1.push((temp));
temp=0;
flag=false;
}
if(str[i]=='(')
{
s2.push(str[i]);
continue;
}
if(str[i]==')')
{
while(s2.top()!='(')
{
calculate(s1,s2);
}
s2.pop();
continue;
}
while(!s2.empty()&&lev(s2.top())>=lev(str[i]))
{
calculate(s1,s2);
}
s2.push(str[i]);
}
}
if(flag==1)
{
s1.push(temp);
temp=0;
flag=false;
}
while(!s2.empty())
{
calculate(s1,s2);
}
cout<<s1.top()<<endl;
return 0;
}
01-21
09-06
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交