Polish Notation
- No parenthesis:
(3 + 4)->+ 3 4
Example: (9 + 6) * (3 - 2) -> 9 6 + 3 2 - *
A simple calculator for Polish notations:
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
int evaluate_rpn(const std::string &expr) {
std::stack<int> stk;
std::istringstream iss(expr);
std::string token;
while (iss >> token) {
if (isdigit(token[0])) {
stk.push(std::stoi(token));
} else {
int b = stk.top();
stk.pop();
int a = stk.top();
stk.pop();
if (token == "+")
stk.push(a + b);
else if (token == "-")
stk.push(a - b);
else if (token == "*")
stk.push(a * b);
else if (token == "/")
stk.push(a / b);
}
}
return stk.top();
}
int main() {
std::cout << evaluate_rpn("3 5 2 * +") << std::endl;
return 0;
}
Whatβs Actually Happening in 3 5 2 * +
This is postfix notation. Think of it like:
βIβll give you the numbers, and then tell you what to do with them.β
Step-by-step Breakdown
Expression: 3 5 2 * +
-
Read
3β push to the stack π₯ Stack:[3] -
Read
5β push to the stack π₯ Stack:[3, 5] -
Read
2β push to the stack π₯ Stack:[3, 5, 2] -
Read
*β pop2and5, multiply them β push result5 * 2 = 10π₯ Stack:[3, 10]
-
Read
+β pop10and3, add them β push result3 + 10 = 13π₯ Stack:[13]
Result = 13
You just evaluated 3 + (5 * 2) without parentheses and without caring about precedence rules.
RPN implicitly does βinwardsβ operations first β the deepest nested expressions get evaluated earliest. But it doesn't track them using parentheses or operator precedence like infix notation. Instead, the stack handles that naturally, because operations only happen when operands are ready.
π Infix β RPN Mental Gymnastics
Letβs take:
(4 + 2) * (3 - 1)
RPN version:
4 2 + 3 1 - *
Why?
4 2 +β gives you 63 1 -β gives you 2- Then
*β6 * 2 = 12
The operators are applied only when their operands are present, and everything is processed left to right. No drama, no ambiguity, no parentheses.
π‘ Why You Should Care
If you ever:
- Write a compiler or interpreter,
- Build a virtual machine (JITs for example),
- Design an AI rule engine,
- Or implement a Lisp-style scripting language,
β¦youβll want RPN-style evaluation. Itβs efficient, deterministic, and ridiculously elegant.