Pagini recente » Cod sursa (job #489444) | Cod sursa (job #2214786) | Cod sursa (job #1865906) | Cod sursa (job #440170) | Cod sursa (job #2843990)
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
stack <char> op;
stack <int> polo;
char s[100001];
int prior(char op){
switch(op){
case '+' : return 1;
case '-' : return 1;
case '*' : return 2;
case '/' : return 2;
}
return 0;
}
int oper(int a, int b, char op){
switch(op){
case '+' : return a + b;
case '-' : return a - b;
case '*' : return a * b;
case '/' : return a / b;
}
}
int main()
{
char x;
int a,b,n = 0,i,j,t;
cin.getline(s,100001);
t = strlen(s);
for(i = 0; i < t; ++i){
if(isdigit(s[i])){
n = 0;
while(i < t && isdigit(s[i])){
n = (n * 10) + (s[i] - '0');
++i;
}
polo.push(n);
i--;
}
if(s[i] == '('){
op.push(s[i]);
}
if(s[i] == ')'){
while(!op.empty() && op.top() != '('){
x = op.top();
op.pop();
a = polo.top();
polo.pop();
b = polo.top();
polo.pop();
polo.push(oper(b,a,x));
}
if(!op.empty()){
op.pop();
}
}
if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
while(!op.empty() && prior(s[i]) <= prior(op.top())){
x = op.top();
op.pop();
a = polo.top();
polo.pop();
b = polo.top();
polo.pop();
polo.push(oper(b,a,x));
}
op.push(s[i]);
}
}
while(!op.empty()){
x = op.top();
op.pop();
a = polo.top();
polo.pop();
b = polo.top();
polo.pop();
polo.push(oper(b,a,x));
}
cout << polo.top();
return 0;
}