const int MAXN = 1e6 + 5;
int n,m;
bool f;
stack<int>st1;
stack<char>st2;
int qpw(int a,int b){
int ans = 1;
while(b){
if(b & 1){
ans*=a;
}
a = a*a;
b >>= 1;
}
return ans;
}
int level(char x){ //返回优先级
if(x == '+' || x == '-')return 1;
else if(x == '*' || x == '/')return 2;
else if(x == '^')return 3;
return 0;
}
//弹出栈顶元素并计算
void calc(stack<int>&st1,stack<char>&st2){
int y = st1.top();st1.pop();
int x = st1.top();st1.pop();
char c = st2.top();st2.pop();
if(c == '+')st1.push(x + y);
else if(c == '-')st1.push(x-y);
else if(c == '*')st1.push(x*y);
else if(c == '/')st1.push(x/y);
else if(c == '^')st1.push(qpw(x,y));
}
int c(int x){
return x!=0;
}
char str[MAXN];
int sum[MAXN];
int main(){
scanf("%s",str+1);
n = strlen(str+1);
for(int i=1;i<=n;i++){
sum[i] += sum[i-1];
if(str[i] == '(')sum[i] ++;
if(str[i] == ')')sum[i] --;
}
f = true;
for(int i=2;i<=n;i++){
if(c(level(str[i])) && c(level(str[i-1]))){
f = false;
break;
}
}
if((n ==1 && c(level(str[1]))) || sum[n] || !f){
printf("NO\n");
return 0;
}
f = false;
int temp = 0;
for(int i=1;i<=n;i++){
//如果是数字
if(str[i] <='9' && str[i] >= '0'){
temp = (temp << 3) + (temp << 1) + (str[i]- '0');
f = true;
}
else{ //符号
if(f){ //先把数字放进去
st1.push(temp);
temp = 0;
f = 0;
}
if(str[i] == '('){
st2.push(str[i]);
continue;
}
if(str[i] == ')'){
while(st2.top() != '(')calc(st1,st2);
st2.pop();
continue;
}
while(!st2.empty() && level(st2.top()) >= level(str[i]))
calc(st1,st2);
st2.push(str[i]);
}
}
if(f){
st1.push(temp);
temp = 0;
f = false;
}
while(st2.size()){
calc(st1,st2);
}
printf("%d\n",st1.top());
return 0;
}
求表达式的值
最新推荐文章于 2021-11-04 16:24:58 发布