1 条题解
-
0
参考答案:
#include<iostream> #include<stack> #include<unordered_map> using namespace std; unordered_map<char, int> p = { {'+',1},{'-',1},{'*',2},{'/',2} }; stack<char> op; stack<int> num; void eval() { int b = num.top(); num.pop(); int a = num.top(); num.pop(); char c = op.top(); op.pop(); int sum = 0; if (c == '+') sum = a + b; if (c == '-') sum = a - b; if (c == '*') sum = a * b; if (c == '/') sum = a / b; num.push(sum); } int main() { string s; cin >> s; for (int i = 0; i < s.size(); ++i) { if (isdigit(s[i])) { int t = 0; while (isdigit(s[i]) && i < s.size()) t = t * 10 + (s[i++] - '0'); i--; num.push(t); } else if (s[i] == '(') op.push('('); else if (s[i] == ')') { while (op.top() != '(') eval(); op.pop(); } else { while (op.size() && p[op.top()] >= p[s[i]]) eval(); op.push(s[i]); } } while (op.size()) eval(); cout << num.top() << endl; return 0; }
- 1
信息
- ID
- 73
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者