-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluate Prefix Expression.cpp
More file actions
132 lines (95 loc) · 2.12 KB
/
Evaluate Prefix Expression.cpp
File metadata and controls
132 lines (95 loc) · 2.12 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
// Evaluate Prefix Expression.cpp
#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
bool IsOperator(string str)
{
return (str == "+" || str == "-" || str == "*" || str == "/") ? true : false;
}
int StringToInt(string str)
{
int I, pos = 0, n, len = str.length();
bool minus = false;
if(str[0] == '-')
{
pos = 1;
minus = true;
}
n = 0;
for(I = pos; I < len; I++)
{
n *= 10;
n += (str[I] - '0');
}
if(minus)
n *= (-1);
return n;
}
void EvalPrefix(vector<string> tokens)
{
stack<int> S;
int res = 0;
for(int I = tokens.size() - 1; I >= 0; I--)
{
string str = tokens[I];
if(IsOperator(str))
{
if(S.empty())
{
cout << "The given prefix expression is not valid.\n";
return;
}
int operand1 = S.top();
S.pop();
if(S.empty())
{
cout << "The given prefix expression is not valid.\n";
return;
}
int operand2 = S.top();
S.pop();
if(str == "+")
res = (operand1 + operand2);
else if(str == "-")
res = (operand1 - operand2);
else if(str == "*")
res = (operand1 * operand2);
else
res = (operand1 / operand2);
S.push(res);
}
else
{
int n = StringToInt(str);
S.push(n);
}
}
if(S.size() > 1)
{
cout << "The given prefix expression is not valid.\n";
return;
}
if(!S.empty())
{
res = S.top();
S.pop();
}
cout << "Output: " << res << '\n';
}
int main()
{
string str;
vector<string> tokens;
while(cin >> str)
tokens.push_back(str);
EvalPrefix(tokens);
return 0;
}
/*
Input:
- + * 2 3 * 5 4 9
Output:
17
*/