小明在你的帮助下,破密了 Ferrari 设的密码门,正要往前走,突然又出现了一个密码
门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是
密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)
输入
输入 1 行,为一个算式。
输出
输出 1行,就是密码。
样例
输入
1+(3+2)*(7^2+6*9)/(2)
输出
258
提示
【限制】
100%的数据满足:算式长度<=30 其中所有数据在 2^31-1 的范围内。
[参考代码]
#include<bits/stdc++.h>
using namespace std;
char str[10000];
int n;
stack<int>s1;//数字
stack<char>s2;//运算符
void calc() {
int y=s1.top();
s1.pop();
int x=s1.top();
s1.pop();
char z=s2.top();
s2.pop();
if(z=='+')
s1.push(x+y);
else if(z=='-')
s1.push(x-y);
else if(z=='*')
s1.push(x*y);
else if(z=='/' )
s1.push(x/y);
else
s1.push(pow(x,y));
}
int level(char x) { //运算等级
if(x=='+'||x=='-')
return 1;
if(x=='*'||x=='/')
return 2;
if(x=='^')
return 3;
return 0;
}
int main() {
scanf("%s",str+1);
n=strlen(str+1);//有效符号个数
//连续运算符
for(int i=1; i<=n; i++) {
if(str[i]!='('&&str[i]!=')'&&(str[i]<'0'||str[i]>'9')&&str[i+1]!='('&&str[i+1]!=')'&&(str[i+1]<'0'||str[i+1]>'9')&&i!=n) {
cout<<"NO";
return 0;
}
if(str[i]=='('&&(str[i+1]=='+'||str[i+1]=='*'||str[i+1]=='/'||str[i+1]=='^')) {
cout<<"NO";
return 0;
}
}
//开头特判
bool tepan=false;
if(str[1]=='-')
tepan=true;
else if(str[2]=='-'&&str[1]=='(')
tepan=true;
//初始化
int temp=0;
bool flag=false;
//核心部分
for(int i=1; i<=n; i++) {
if(str[i]>='0'&&str[i]<='9') {
temp=temp*10+str[i]-48;
flag=true;
} else {
if(flag==true) {
if(tepan==true)
s1.push(-temp);
else
s1.push(temp);
temp=0;
flag=false;
tepan=false;
}
if(str[i]=='(') {
s2.push(str[i]);
//符号特判
if(str[i+1]=='-')
tepan=true;
continue;
} else if(str[i]==')') {
while(s2.top()!='(')
calc();
s2.pop();
continue;
}
while(s2.empty()==false&&level(s2.top())>=level(str[i]))
calc();
if((str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'||str[i]=='^')&&tepan==false)
s2.push(str[i]);
}
}
if(flag==true) {
s1.push(temp);
temp=0;
flag=false;
}
while(s2.empty()==false)
calc();
if(s2.empty()==false||s1.size()>1) {
cout<<"NO";
return 0;
}
cout<<s1.top();
return 0;
}