From b71f3d76403ceb4c922a50d14c20315bb402d0ae Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 30 Jan 2024 10:31:30 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB150.=20Evaluate=20Reverse=20?= =?UTF-8?q?Polish=20Notation=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/evaluate-reverse-polish-notation.cpp | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 cpp/evaluate-reverse-polish-notation.cpp diff --git a/cpp/evaluate-reverse-polish-notation.cpp b/cpp/evaluate-reverse-polish-notation.cpp new file mode 100644 index 0000000..58cddbe --- /dev/null +++ b/cpp/evaluate-reverse-polish-notation.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include + +class Solution { + static auto get_function(const std::string &op) + -> std::function { + if (op == "+") { + return std::plus{}; + } else if (op == "-") { + return std::minus{}; + } else if (op == "*") { + return std::multiplies{}; + } else if (op == "/") { + return std::divides{}; + } + + assert(false); + } + + public: + auto evalRPN(const std::vector &tokens) -> int { + std::vector stack; + + for (const auto &token : tokens) { + if (token == "+" || token == "-" || token == "*" || token == "/") { + assert(stack.size() >= 2); + + int right = stack.back(); + stack.pop_back(); + int left = stack.back(); + stack.pop_back(); + + stack.push_back(get_function(token)(left, right)); + } else { + stack.push_back(std::stoi(token)); + } + } + + return stack.back(); + } +}; + +int main() { + Solution s; + + assert(s.evalRPN(std::vector{ + {"2"}, {"1"}, {"+"}, {"3"}, {"*"}}) == 9); + assert(s.evalRPN(std::vector{ + {"4"}, {"13"}, {"5"}, {"/"}, {"+"}}) == 6); + assert(s.evalRPN(std::vector{{"10", "6", "9", "3", "+", "-11", + "*", "/", "*", "17", "+", "5", + "+"}}) == 22); + + return 0; +}