#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int greatest_common_divisor(int x,int y) {
while (y) {
int tmp = x % y;
x = y;
y = tmp;
}
return x;
}
pair<int, int> calculate(string s) {
vector<pair<int,int>> digits;
vector<char> nums;
stack<char> ops;
unordered_map<char, int> level = { {'-',1},{'+',1},{'*',2},{'/',2} };
int i = 0, n = s.length();
while (i < n) {
if (isdigit(s[i])) {
int num = 0;
do {
num = num * 10 + s[i++] - '0';
} while (i < n && isdigit(s[i]));
nums.push_back('N');
digits.push_back({num,1});
}
else if (ops.empty() || s[i] == '(') {
ops.push(s[i++]);
}
else if (s[i] == ')') {
while (!ops.empty() && ops.top() != '(') {
nums.push_back(ops.top());
ops.pop();
}
ops.pop();
++i;
}
else if (level[s[i]] < level[ops.top()]) {
do {
nums.push_back(ops.top());
ops.pop();
} while (!ops.empty() && level[s[i]] < ops.top());
}
else {
ops.push(s[i++]);
}
}
while (!ops.empty()) {
nums.push_back(ops.top());
ops.pop();
}
int k = 0;
stack<pair<int,int>> cal;
for (char ch : nums) {
if (ch == 'N') {
cal.push(digits[k++]);
}
else{
pair<int, int> right = cal.top();
cal.pop();
pair<int, int> left = cal.top();
if (ch == '*') {
cal.top().first = left.first * right.first;
cal.top().second = left.second * right.second ;
}
else if (ch == '/') {
cal.top().first = left.first * right.second;
cal.top().second = left.second * right.first;
}
else if (ch == '+') {
cal.top().first = left.first * right.second + right.first * left.second;
cal.top().second = left.second * right.second;
}
else if (ch == '-') {
cal.top().first = left.first * right.second - right.first * left.second;
cal.top().second = left.second * right.second;
}
int gmd = greatest_common_divisor(cal.top().first, cal.top().second);
cal.top().first /= gmd;
cal.top().second /= gmd;
}
}
return cal.top();
}
};
int main() {
Solution s;
pair<int, int> pr = s.calculate("(11+12)/3-4/3");
cout << pr.first << "/" << pr.second;
}
符号运算OD
于 2024-03-19 23:28:57 首次发布