#include#include #include #include #include using namespace std; stack nums; stack operators; int priority(char ch) { if(ch == '+' || ch == '-') return 1; if(ch == '/' || ch == '*') return 2; if(ch == '^') return 3; return 0; } void calc() { int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); char ch = operators.top(); operators.pop(); if(ch == '+') nums.push(a+b); else if(ch == '-') nums.push(b-a); else if(ch == '*') nums.push(a*b); else if(ch == '/') nums.push(b/a); else if(ch == '^') nums.push(pow(b,a)); } bool check(string str) { stack s; for(int i = 0; str[i] != '@'; i++) { if(str[i] == '(') s.push(str[i]); if(str[i] == ')') if(!s.empty()) s.pop(); else return false; if(str[i] == '/' && str[i+1] == '0') return false; } return true; } int main() { string str; cin >> str; if(!check(str)) { cout << "NO" << endl; return 0; } int num = 0; bool flag = false; for(int i = 0; str[i] != '@'; i++) { if(str[i] >= '0' && str[i] <= '9') { num = num*10 + str[i] - '0'; flag = true; } else { if(flag) { nums.push(num); flag = false; num = 0; } if(str[i] == '(') { operators.push(str[i]); continue; } if(str[i] == ')') { while(operators.top() != '(') calc(); operators.pop(); continue; } while(!operators.empty() && priority(operators.top()) >= priority(str[i])) calc(); operators.push(str[i]); } } if(flag) nums.push(num); while(!operators.empty()) calc(); cout << nums.top() << endl; return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)