1
+ #include < iostream>
2
+ #include < stack>
3
+ #include < string>
4
+ #include < cmath>
5
+ #include < vector>
6
+ #include < algorithm>
7
+ #include < cctype>
8
+
9
+ bool isOperator (const std::string &s) {
10
+ return s == " +" || s == " -" || s == " *" || s == " /" ;
11
+ }
12
+
13
+ bool isNumber (const std::string &s) {
14
+ return !s.empty () && std::all_of (s.begin (), s.end (), [](char c) { return std::isdigit (c) || c == ' .' ; });
15
+ }
16
+
17
+ float evaluate (float a, float b, const std::string &op) {
18
+ if (op == " +" ) return a + b;
19
+ if (op == " -" ) return a - b;
20
+ if (op == " *" ) return a * b;
21
+ if (op == " /" ) return a / b;
22
+ throw std::invalid_argument (" Unknown operator" );
23
+ }
24
+
25
+ float prefixEvaluation (const std::vector<std::string> &expression) {
26
+ std::stack<float > stack;
27
+
28
+ // Traverse the expression from right to left
29
+ for (auto it = expression.rbegin (); it != expression.rend (); ++it) {
30
+ const std::string &token = *it;
31
+
32
+ if (isNumber (token)) {
33
+ stack.push (std::stof (token));
34
+ } else if (isOperator (token)) {
35
+ if (stack.size () < 2 ) {
36
+ throw std::invalid_argument (" Invalid prefix expression" );
37
+ }
38
+ float op1 = stack.top (); stack.pop ();
39
+ float op2 = stack.top (); stack.pop ();
40
+ float result = evaluate (op1, op2, token);
41
+ stack.push (result);
42
+ }
43
+ }
44
+
45
+ if (stack.size () != 1 ) {
46
+ throw std::invalid_argument (" Invalid prefix expression" );
47
+ }
48
+
49
+ return stack.top ();
50
+ }
51
+
52
+ int main () {
53
+ // Example expressions
54
+ std::vector<std::string> expression1 = {" +" , " *" , " 2" , " 3" , " 1" }; // Equivalent to (2 * 3) + 1
55
+ std::vector<std::string> expression2 = {" -" , " +" , " 100" , " 200" , " /" , " 5" , " 2" }; // Equivalent to (100 + 200) - (5 / 2)
56
+
57
+ try {
58
+ float result1 = prefixEvaluation (expression1);
59
+ std::cout << " Result of expression1: " << result1 << std::endl; // Expected output: 7
60
+
61
+ float result2 = prefixEvaluation (expression2);
62
+ std::cout << " Result of expression2: " << result2 << std::endl; // Expected output: 297.5
63
+ } catch (const std::invalid_argument &e) {
64
+ std::cerr << e.what () << std::endl;
65
+ }
66
+
67
+ return 0 ;
68
+ }
0 commit comments