aboutsummaryrefslogtreecommitdiff
path: root/other/eval_reverse_polish_notation.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/eval_reverse_polish_notation.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/eval_reverse_polish_notation.cpp')
-rw-r--r--other/eval_reverse_polish_notation.cpp46
1 files changed, 46 insertions, 0 deletions
diff --git a/other/eval_reverse_polish_notation.cpp b/other/eval_reverse_polish_notation.cpp
new file mode 100644
index 0000000..4cd39b8
--- /dev/null
+++ b/other/eval_reverse_polish_notation.cpp
@@ -0,0 +1,46 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ int evalRPN(vector<string> &tokens) {
+ unordered_map<string, function<int(int, int)>> umf = {
+ {"+", [](long a, long b) { return a + b; }},
+ {"-", [](long a, long b) { return a - b; }},
+ {"*", [](long a, long b) { return a * b; }},
+ {"/", [](long a, long b) { return a / b; }}};
+ stack<long> stk;
+ for (string &s : tokens) {
+ if (!umf.count(s))
+ stk.push(stoi(s));
+ else {
+ long op1 = stk.top();
+ stk.pop();
+ long op2 = stk.top();
+ stk.pop();
+ stk.push(umf[s](op2, op1));
+ }
+ }
+ return static_cast<int>(stk.top());
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<string> tokens1 = {"2", "1", "+", "3", "*"};
+ // output: 9
+ // ((2 + 1) * 3)
+ cout << obj.evalRPN(tokens1);
+ vector<string> tokens2 = {"4", "13", "5", "/", "+"};
+ // output: 6
+ // (4 + (13 / 5))
+ cout << obj.evalRPN(tokens2);
+ vector<string> tokens3 = {"10", "6", "9", "3", "+", "-11", "*",
+ "/", "*", "17", "+", "5", "+"};
+ // output: 22
+ // ((10 * (6 / (12 * -11))) + 17) + 5
+ // ((10 * (6 / -132)) + 17) + 5
+ // ((10 * 0) + 17) + 5
+ // (0 + 17) + 5
+ // 17 + 5
+ cout << obj.evalRPN(tokens3);
+}