RE前两个点,求调
查看原帖
RE前两个点,求调
695685
AssiduousCoding楼主2024/7/12 15:53
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
#include <unordered_map>

using namespace std;

string str;
stack<int> num;
stack<char> op;

int qmi(int a, int k) {
	int res = 1;
	while (k) {
		if (k & 1) res *= a;
		k >>= 1;
		a *= a;
	}
	return res;
}

void eval() {
	int b = num.top(); num.pop();
	int a = num.top(); num.pop();
	char c = op.top(); op.pop();
	if (c == '+') num.push(a + b);
	else if (c == '*') num.push(a * b);
	else if (c == '-') num.push(a - b);
	else if (c == '/' && b != 0) num.push(a / b);
	else num.push(qmi(a, b));
}

int main() {
	cin >> str;
	unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3}};

	for (int i = 0; i < (int)str.size(); i ++ ) {
		if (isdigit(str[i])) {
			int j = i, x = 0;
			while (j < (int)str.size() && isdigit(str[j])) x = x * 10 + str[j ++ ] - '0';
			i = j - 1;
			num.push(x);
		} else if (str[i] == '(') op.push('(');
		else if (str[i] == ')') {
			while (op.top() != '(') eval();
			if (op.size()) op.pop();
		} else {
			while (op.size() && pr[op.top()] >= pr[str[i]]) eval();
			op.push(str[i]);
		}
	}
	while (op.size()) eval();

	cout << num.top() << endl;

	return 0;
}
2024/7/12 15:53
加载中...