-
Notifications
You must be signed in to change notification settings - Fork 0
/
a.cpp
120 lines (111 loc) · 2.2 KB
/
a.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <iostream>
#include <stdlib.h>
using namespace std;
struct StNode
{
int value;
StNode *next;
};
StNode *top = NULL;
void push(int value)
{
StNode *ptr = (StNode *)malloc(sizeof(StNode));
ptr->value = value;
ptr->next = top;
top = ptr;
}
char pop()
{
if (top == NULL)
{
return -1;
}
int value = top->value;
StNode *tmp = top;
top = top->next;
free(tmp);
return value;
}
string reverseStr(string str)
{
string revStr;
for (int i = 0; i < str.length(); i++)
{
revStr = str[i] + revStr;
}
return revStr;
}
int prefixEvaluation(string prefixEq)
{
string revPrefixEq = reverseStr(prefixEq);
for (int i = 0; i < revPrefixEq.length(); i++)
{
char currChar = revPrefixEq[i];
// cout << currChar << endl;
if (currChar > 47 && currChar < 58)
{
int value = currChar - 48;
push(value);
}
else
{
int lop = pop();
int rop = pop();
// cout << lop << rop << currChar;
int tmp;
switch (currChar)
{
case '*':
tmp = lop * rop;
break;
case '/':
tmp = lop / rop;
break;
case '%':
tmp = lop % rop;
break;
case '+':
tmp = lop + rop;
break;
case '-':
tmp = lop - rop;
break;
case '<':
tmp = lop < rop;
break;
case '>':
tmp = lop > rop;
break;
case '=':
tmp = lop == rop;
break;
case '!':
tmp = lop != rop;
break;
case '&':
tmp = lop && rop;
break;
case '|':
tmp = lop || rop;
break;
default:
break;
}
push(tmp);
}
}
return pop();
}
int main()
{
string infixEq1 = "a+b*c/d*x-f*d";
string prefixEq1 = "-+a*/*bcdx*fd";
// let values a = 2, b = 1, c = 3, d = 1, f = 2, x = 2
// int result = prefixEvaluation("-+2*/*1312*21");
string infixEq2 = "a+b*(c-d)<x&(c!y|x+y<5)";
string prefixEq2 = "&<+a*b-cdx|!cy<+xy5";
// let values a = 2, b= 1, c = 3, d = 1, x = 2, y = 4
int result = prefixEvaluation("&<+2*1-312|!34<+245");
cout << "Answer is " << result << endl;
cout << "Note :- 1 and 0 also indicates true and false!!! " << endl;
}