1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <iostream> #include <stack> #include <string> using namespace std; const int M = 200; const int INF = 0x3f; int quick_pow(int x, int y) { if (y == 0) return 1; else if (y % 2 == 0) return quick_pow(x * x, y / 2); else return quick_pow(x * x, y / 2) * x; }
bool operation(stack<int>&NUM, stack<char>&OP) { int b = NUM.top(); NUM.pop(); int a = NUM.top(); NUM.pop(); char op = OP.top(); OP.pop(); if (op == '+') NUM.push(a + b); else if (op == '-') NUM.push(a - b); else if (op == '*') NUM.push(a * b); else if (op == '/') { if (b == 0) return false; NUM.push(a / b); } else NUM.push(quick_pow(a, b)); return true; } int cal(stack<int>&NUM, stack<char>&OP,string s) { int p[M]; p['+'] = p['-'] = 1; p['*'] = p['/'] = 2; p['^'] = 3; int n = s.size(); for (int i = 0; i < n; i++) { if (s[i] >= '0' && s[i] <= '9') { int tmp = 0; while (s[i] >= '0' && s[i] <= '9') tmp = 10 * tmp + s[i++] - '0'; i--; NUM.push(tmp); } else if (s[i] == '(') OP.push('('); else if (s[i] == ')') { while (OP.top() != '(') { bool sign=operation(NUM, OP); if (sign == 0) return INF; } OP.pop(); } else { while (!OP.empty() && OP.top() != '(' && p[s[i]] <= p[OP.top()]) { bool sign = operation(NUM, OP); if (sign == 0) return INF; } OP.push(s[i]); } } while (!OP.empty()) { bool sign = operation(NUM, OP); if (sign == 0) return INF; } return NUM.top(); } int main() { string s; while (cin >> s) { int n = s.size(); stack<int>NUM; stack<char>OP; int ans = cal(NUM, OP, s); if (ans == INF) cout << "INVALID" << endl; else cout << ans << endl; } return 0; }
|