Run ID | 作者 | 问题 | 语言 | 测评结果 | 分数 | 时间 | 内存 | 代码长度 | 提交时间 |
---|---|---|---|---|---|---|---|---|---|
180025 | C班 郑筱橦 | 表达式求值 | C++ | 解答错误 | 10 | 0 MS | 252 KB | 1228 | 2024-08-21 12:57:53 |
#include<iostream> #include<string> #include<map> #include<stack> using namespace std; stack<int> num; stack<char> op; void eval(){ int b = num.top(); num.pop(); int a = num.top(); num.pop(); char c = op.top(); op.pop(); int x; if(c == '+') x = a + b; else if(c == '-') x = a - b; else if(c == '*') x = a * b; else x = a / b; num.push(x); } int main(){ string s; cin >> s; map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; for(int i = 0; i < s.size(); i++){ if(isdigit(s[i])){ int j = i, operand = 0; while(j < s.size() && isdigit(s[j])){ operand = operand * 10 + s[j] - '0'; j++; } num.push(operand); i = j - 1; }else if(s[i] == '('){ op.push(s[i]); }else if(s[i] == ')'){ while(op.top() != '(') eval(); op.pop(); }else{ while(op.size() && op.top() != '(' && mp[op.top()] >= mp[s[i]]) eval(); op.push(s[i]); } } while(op.size()) eval(); cout << num.top() << endl; return 0; }