Pagini recente » Cod sursa (job #1961808) | Cod sursa (job #1188674) | Cod sursa (job #1702657) | Cod sursa (job #2273153) | Cod sursa (job #2302830)
#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<int> numbas;
stack<char> operators;
int GetPriority(char c)
{
if(c == '+' || c == '-'){
return 0;
}else if(c == '*' || c == '/'){
return 1;
}else if(c == '('){
return -1;
}
}
bool IsNumba(char c)
{
return (c >= '0' && c <= '9');
}
int ToNumba(char c)
{
return (c - '0');
}
int Eval(char op, int a, int b)
{
if(op == '+'){
return a+b;
}else if(op == '-'){
return a-b;
}else if(op == '*'){
return a*b;
}else if(op == '/'){
return a/b;
}
return 0;
}
int Dijkstra(string s)
{
char c;
for(int i = 0; i < s.size(); i++){
c = s[i];
if(IsNumba(c)){
int a = ToNumba(c);
while(IsNumba(s[i+1])){
a *= 10;
a += ToNumba(s[i+1]);
i++;
}
numbas.push(a);
}else if(c == '('){
operators.push(c);
}else if(c == ')'){
while(operators.top() != '('){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
operators.pop();
}else{
while(!operators.empty() && GetPriority(operators.top()) > GetPriority(c)){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
operators.push(c);
}
}
while(!operators.empty()){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
return numbas.top();
}
int main()
{
cout << Dijkstra("(1+1)*13+10/2") << endl;
return 0;
}