From 51d955fbdada4400c8efd504d637b4ece6fcee22 Mon Sep 17 00:00:00 2001 From: Stoycho Kyosev Date: Wed, 12 Oct 2022 15:42:41 +0300 Subject: add seminar02 --- Seminar02/task03.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Seminar02/task03.cpp (limited to 'Seminar02/task03.cpp') diff --git a/Seminar02/task03.cpp b/Seminar02/task03.cpp new file mode 100644 index 0000000..d460551 --- /dev/null +++ b/Seminar02/task03.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include + +bool isOperation(char c) { + return (c == '+') || (c == '-') || (c == '*') || (c == '/'); +} + +bool isDigit(char c) { + return c >= '0' && c <= '9'; +} + +int eval(int fst, int snd, char op) { + assert(isOperation(c)); + + switch (op) { + case '+': + return fst + snd; + case '-': + return fst - snd; + case '*': + return fst * snd; + case '/': + return fst / snd; + } +} + +int RPN(const std::string& str) { + std::stack numbers; + + for (size_t i = 0; i < str.size(); i++) { + if(isOperation(str[i])) { + int snd = numbers.top(); + numbers.pop(); + + int fst = numbers.top(); + numbers.pop(); + + numbers.push(eval(fst, snd, str[i])); + } + else if(str[i] != ' ') { + int number = 0; + while(i < str.size() && isDigit(str[i])) { + number *= 10; + number += str[i] - '0'; + i++; + } + i--; + numbers.push(number); + } + } + + return numbers.top(); +} + +int main() { + std::cout << RPN("9 3 4 * - 2 5 * -"); +} \ No newline at end of file -- cgit v1.3.1-23-gd82d