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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> #include <vector> #include <stack>
using namespace std;
bool isNumber(char x) { if (x >= '0' && x <= '9') return true; return false; }
bool isOperate(char opt) { if(opt=='+' || opt=='-' || opt=='*' || opt=='/' || opt=='(' || opt==')' || opt=='#') return true; else return false; }
int priority(char x) { if (x == '+' || x == '-') return 0; else if (x == '*' || x == '/') return 1; else if (x == '(' || x == ')') return -1; else if (x == '#') return -2; }
int toCalculate(int x, char opt, int y) { switch(opt){ case '+': return x+y; case '-': return x-y; case '*': return x*y; case '/': return x/y; } }
char compare(char a, char b) { if(priority(a) > priority(b)) return '>'; else if(priority(a) < priority(b)) return '<'; return '='; }
int calculate(string str) { str += '#'; stack<int> number; stack<char> operators; operators.push('#'); char top;
for(unsigned int i = 0; i < str.size(); i++){ if(isNumber(str[i])){ int data = 0; string temp; temp += str[i]; while(isNumber(str[++i])){ temp += str[i]; } for(unsigned int j = 0; j < temp.size(); j++){ data = data*10 + (temp[j] - '0'); } number.push(data); } if(!isNumber(str[i]) && isOperate(str[i])){ top = operators.top(); if(str[i] == '('){ operators.push(str[i]); continue; } switch(compare(top, str[i])){ case '<' : operators.push(str[i]); break; case '>' : case '=' : while(compare(top, str[i]) == '>' || compare(top, str[i]) == '='){ if(top == '#' && str[i] == '#') return number.top(); else if(top == '(' && str[i] == ')') ++i; else{ int a = number.top(); number.pop(); int b = number.top(); number.pop(); number.push(toCalculate(b, top, a)); } operators.pop(); top = operators.top(); } operators.push(str[i]); break; } } }
}
int main() { string str; cin >> str; cout << calculate(str); return 0; }
|