View Code of Problem 94

#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
int cal(stack<int>stack,char c) {
	while (stack.size()!=1) {
		int left = stack.top();
		stack.pop();
		int right = stack.top();
		stack.pop();
		if (c == '+') {
			stack.push(left + right);
		}
		if (c == '-') {
			stack.push(left - right);
		}
		if (c == '*') {
			stack.push(left * right);
		}
		if (c == '/') {
			stack.push(left / right);
		}
	}
	return stack.top();
}
int main()
{
	string str;
	getline(cin, str);
	stack<char>oper;
	stack<char>num;
	string strnum;
	for (int i = 0; i < str.size(); i++) {
		if (str[i] == '(') {
			num.push(str[i]);
		}
		else if (isdigit(str[i])) {
			strnum += str[i];
		}
		else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
			oper.push(str[i]);
		}
		else if (str[i] == ' ') {
			if (strnum != "") {
				num.push(stoi(strnum));
				strnum = "";
			}
		}
		else {
			if (strnum != "") {
				num.push(stoi(strnum));
				strnum = "";
			}
			char c = oper.top();
			oper.pop();
			stack<int>s;
			while (num.top() != '(') {
				s.push(num.top());
				num.pop();
			}
			num.pop();
			int res=cal(s, c);
			num.push(res);
		}
	}
	printf("%d\n", num.top());
	
	return 0;
}

Double click to view unformatted code.


Back to problem 94