Pagini recente » Cod sursa (job #633213) | Cod sursa (job #3291316) | Cod sursa (job #1705780) | Cod sursa (job #445324) | Cod sursa (job #2232875)
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;
string infix;
vector<string> postfix;
const char *OPERATORS = "+-/*()";
vector<int> priority(256);
bool isOperator(char c) {
if (strchr(OPERATORS, c) != nullptr) {
return true;
}
return false;
}
bool isStringOperator(string s) {
if (s.size() != 1)
return false;
char c = s[0];
return isOperator(c);
}
void convertInfixToPostfix() {
stack<char> operators;
for (int i = 0; i < infix.size(); ++i) {
if (isOperator(infix[i])) {
if (infix[i] == '(') {
operators.push(infix[i]);
} else if (infix[i] == ')') {
do {
char op = operators.top();
operators.pop();
postfix.push_back(string(1, op));
} while(operators.top() != '(');
operators.pop();
} else {
while(!operators.empty() && priority[operators.top()] >= priority[infix[i]]) {
char op = operators.top();
operators.pop();
postfix.push_back(string(1, op));
}
operators.push(infix[i]);
}
} else {
string number;
do {
number += infix[i];
i++;
} while(!isOperator(infix[i]) && i < infix.size());
postfix.push_back(number);
i--;
}
}
while (!operators.empty()) {
string op = string(1, operators.top());
operators.pop();
postfix.push_back(op);
}
}
long long calculate(long long nr1, long long nr2, string op) {
switch(op[0]) {
case '+':
return nr1 + nr2;
case '-':
return nr2 - nr1;
case '*':
return nr1 * nr2;
case '/':
return nr2 / nr1;
}
}
void printPostfixExpressionResult() {
stack<long long> numbers;
for (int i = 0; i < postfix.size(); ++i) {
if (isStringOperator(postfix[i])) {
long long nrOne = numbers.top(); numbers.pop();
long long nrTwo = numbers.top(); numbers.pop();
long long result = calculate(nrOne, nrTwo, postfix[i]);
numbers.push(result);
} else {
numbers.push(stoll(postfix[i]));
}
}
cout << numbers.top();
}
int main() {
priority['+'] = 1;
priority['-'] = 1;
priority['/'] = 2;
priority['*'] = 2;
getline(cin, infix);
convertInfixToPostfix();
printPostfixExpressionResult();
return 0;
}