-
Notifications
You must be signed in to change notification settings - Fork 4
/
rpn.cpp
41 lines (37 loc) · 1.03 KB
/
rpn.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
// A basic Reverse Polish Notation (RPN) calculator
#include <iostream>
#include <sstream>
#include <stack>
#include <stdexcept>
double RPN(std::string expr) {
std::stack<double> stck;
std::stringstream ss{expr};
std::string token;
while (ss >> token) {
if (token != "+" && token != "-" && token != "*" && token != "/") {
stck.push(std::stod(token));
} else {
double x = stck.top();
stck.pop();
double y = stck.top();
stck.pop();
if (token == "+") {
stck.push(y + x);
} else if (token == "-") {
stck.push(y - x);
} else if (token == "*") {
stck.push(y * x);
} else if (token == "/") {
stck.push(y / x);
}
}
}
if (stck.size() != 1) {
throw std::runtime_error("Invalid expression!");
}
return stck.top();
}
int main() {
std::string expr = "10 4 3 + 2 * -";
std::cout << RPN(expr) << std::endl;
}