Solution
cookiebus
2022-11-12 11:16:51
24
返回题目
#include <bits/stdc++.h>
using namespace std;
string expr;
int getPriority(char c) {
if (c == '(')
return 1;
if (c == ')')
return 2;
if (c == '+' || c == '-')
return 3;
if (c == '*' || c == '/')
return 4;
return -1;
}
string trans(string expr) {
int len = expr.size() - 1;
string ret = "";
stack<char> op;
bool flag = false;
string num = "";
for (int i = 0; i < len; ++i) {
char c = expr[i];
if (c >= '0' && c <= '9') {
num += c;
flag = true;
}
if (getPriority(c) != -1 && flag) {
ret += num + " ";
flag = false;
num = "";
}
if (c == '(')
op.push(c);
else if (c == ')') {
while (!op.empty() && op.top() != '(') {
ret.push_back(op.top());
op.pop();
}
if (op.empty()) {
cout << "NO" << endl;
exit(0);
}
op.pop();
} else if (getPriority(c) != -1) {
while (!op.empty() && getPriority(op.top()) >= getPriority(c)) {
ret.push_back(op.top());
op.pop();
}
op.push(c);
}
}
if (flag)
ret += num + " ";
while (!op.empty()) {
if (op.top() == '(') {
cout << "NO" << endl;
exit(0);
}
ret.push_back(op.top());
op.pop();
}
return ret;
}
int main() {
getline(cin, expr);
expr = trans(expr);
stack<int> val;
int len = expr.size();
for (int i = 0; i < len; ++i) {
char c = expr[i];
if (c == ' ')
continue;
if (c >= '0' && c <= '9') {
int num = c - '0';
while (expr[i + 1] != ' ') {
i++;
num = num * 10 + expr[i] - '0';
}
val.push(num);
} else {
if (val.size() < 2) {
cout << "NO" << endl;
return 0;
}
int y = val.top();
val.pop();
int x = val.top();
val.pop();
if (c == '*')
val.push(x * y);
else if (c == '/') {
val.push(x / y);
} else if (c == '+') {
val.push(x + y);
} else if (c == '-') {
val.push(x - y);
}
}
}
if (val.size() >= 2)
cout << "NO" << endl;
else
cout << val.top() << endl;
return 0;
}
{{ vote && vote.total.up }}
共 2 条回复
%%%
%%%