-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPN.cpp
More file actions
90 lines (74 loc) · 1.62 KB
/
RPN.cpp
File metadata and controls
90 lines (74 loc) · 1.62 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
#include "RPN.hpp"
RPN::RPN() {}
RPN::RPN(const RPN &other) : _stack(other._stack) {}
RPN &RPN::operator=(const RPN &other)
{
if (this != &other)
_stack = other._stack;
return *this;
}
RPN::~RPN() {}
bool RPN::isOperator(const char token) const
{
return token == '+' || token == '-' || token == '*' || token == '/';
}
bool RPN::isNumber(const char token) const
{
return token >= '0' && token <= '9';
}
void RPN::ApplyOp(const char op)
{
if (_stack.size() < 2)
throw std::runtime_error("Error");
int b = _stack.top();
_stack.pop();
int a = _stack.top();
_stack.pop();
switch (op)
{
case '+':
_stack.push(a + b);
break;
case '-':
_stack.push(a - b);
break;
case '*':
_stack.push(a * b);
break;
case '/':
if (b == 0)
throw std::runtime_error("Error");
_stack.push(a / b);
break;
default:
throw std::runtime_error("Error");
}
}
int RPN::calculate(const std::string &expression)
{
std::istringstream iss(expression);
std::string token;
while (iss >> token)
{
if (token.empty())
continue;
if (token.length() != 1)
throw std::runtime_error("Error");
char c = token[0];
if (isNumber(c))
{
_stack.push(c - '0');
}
else if (isOperator(c))
{
ApplyOp(c);
}
else
{
throw std::runtime_error("Error");
}
}
if (_stack.size() != 1)
throw std::runtime_error("Error");
return _stack.top();
}