参考别人的
#include <iostream> #include <bits/stdc++.h> using namespace std; int priority(char c) { if(c == '+' || c=='-') { return 111; } if(c == '*' || c=='/') { return 222; } return 0; } string normalize(string s) { for(int i=0; i<s.length(); i++) { if(s[i] == '[') s[i] = '('; if(s[i] == '{') s[i] = '('; if(s[i] == ']') s[i] = ')'; if(s[i] == '}') s[i] = ')'; } return s; } int apply_calc(int a, int b, char op) { int result ; switch (op) { case '+': result = a+b; break; case '-': result = a-b; break; case '*': result = a*b; break; case '/': result = a/b; break; } return result; } void calc(stack<char>& ops, stack<int>& nums) { int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); nums.push(apply_calc(a, b , op)); } int compute(string& s) { stack<char> Ops; stack<int> Nums; int n = s.length(); for(int i=0; i<n; i++) { if(s[i]=='-' && (i==0 || s[i-1] == '(')) { int number = 0; int j=i+1; bool is_Number = false; while(j<n && isdigit(s[j])) { is_Number=true; number = number*10 + (s[j] - '0'); j++; } if(is_Number) Nums.push(-1*number); i = j; } else if(isdigit(s[i])) { int j = i; int number = 0; while(j < n && isdigit(s[j])) { number = number * 10 + s[j] - '0'; j++; } Nums.push(number); i = j; } if(s[i] == '(') { Ops.push(s[i]); } else if(s[i] == ')') { while(Ops.empty()==false && Ops.top() != '(') { calc(Ops, Nums); } if(!Ops.empty()) Ops.pop(); } else//operator { while(Ops.empty()==false && priority(Ops.top()) >= priority(s[i])) { calc(Ops, Nums); } Ops.push(s[i]); } } while(Ops.empty() == false && Nums.size() != 1) { calc(Ops, Nums); } return Nums.top(); } int main() { std::string str; getline(cin, str); str = normalize(str); int res = compute(str); cout << res; }