-
Notifications
You must be signed in to change notification settings - Fork 1
/
MathematicalExpressionEvaluator.cpp
126 lines (99 loc) · 2.83 KB
/
MathematicalExpressionEvaluator.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
121
122
123
124
125
126
//
// Max Base
// https://github.com/BaseMax/MathematicalExpressionEvaluator
// 06/24/2023
//
#include <stack>
#include <string>
#include <iostream>
using namespace std;
int precedence(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
int applyOperator(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
int evaluateExpression(const string& expression) {
stack<int> values;
stack<char> operators;
int i = 0;
while (i < expression.length()) {
char c = expression[i];
if (c == '(') {
operators.push(c);
} else if (isdigit(c)) {
int num = 0;
while (i < expression.length() && isdigit(expression[i])) {
num = num * 10 + (expression[i] - '0');
i++;
}
i--;
values.push(num);
} else if (c == ')') {
while (operators.top() != '(') {
char op = operators.top();
operators.pop();
int b = values.top();
values.pop();
int a = values.top();
values.pop();
values.push(applyOperator(a, b, op));
}
operators.pop(); // Discard the opening parenthesis
} else {
while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
char op = operators.top();
operators.pop();
int b = values.top();
values.pop();
int a = values.top();
values.pop();
values.push(applyOperator(a, b, op));
}
operators.push(c);
}
i++;
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
int b = values.top();
values.pop();
int a = values.top();
values.pop();
values.push(applyOperator(a, b, op));
}
return values.top();
}
int main() {
// Test case 1: (5+((8+2)*2))
string expression1 = "(5+((8+2)*2))";
int result1 = evaluateExpression(expression1);
cout << expression1 << " = " << result1 << endl;
// Test case 2: ((6*(2+1))*(3+(3+1)))
string expression2 = "((6*(2+1))*(3+(3+1)))";
int result2 = evaluateExpression(expression2);
cout << expression2 << " = " << result2 << endl;
// User input
string expression;
cout << "Enter the mathematical expression: ";
getline(cin, expression);
int result = evaluateExpression(expression);
cout << "Result: " << result << endl;
return 0;
}