-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluator.cpp
More file actions
52 lines (45 loc) · 1.47 KB
/
Copy pathevaluator.cpp
File metadata and controls
52 lines (45 loc) · 1.47 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
#include "evaluator.h"
#include <cmath>
int Evaluator::applyOp(int a, int b, char op) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if(b == 0) throw std::runtime_error("Division by zero");
return a / b;
case '^': return static_cast<int>(std::pow(a, b));
default: throw std::runtime_error("Unknown operator");
}
}
int Evaluator::evaluatePostfix(const std::string& postfix) {
std::stack<int> st;
for(char c : postfix) {
if(std::isdigit(c)) {
st.push(c - '0'); // simple single-digit numbers
} else {
if(st.size() < 2) throw std::runtime_error("Malformed expression");
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(applyOp(a, b, c));
}
}
if(st.size() != 1) throw std::runtime_error("Malformed expression");
return st.top();
}
int Evaluator::evaluatePrefix(const std::string& prefix) {
std::stack<int> st;
for(auto it = prefix.rbegin(); it != prefix.rend(); ++it) {
char c = *it;
if(std::isdigit(c)) {
st.push(c - '0');
} else {
if(st.size() < 2) throw std::runtime_error("Malformed expression");
int a = st.top(); st.pop();
int b = st.top(); st.pop();
st.push(applyOp(a, b, c));
}
}
if(st.size() != 1) throw std::runtime_error("Malformed expression");
return st.top();
}