符号运算OD

#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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值