Krasnopolskiy

Tree calculator

Nov 25th, 2020 (edited)
600
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int priority(char op)
  6. {
  7.     if (op == '+' or op == '-')
  8.         return 1;
  9.     if (op == '*' or op == '/')
  10.         return 2;
  11.     return 100 - isdigit(op);
  12. }
  13.  
  14. int last_op(string exp, int left, int right)
  15. {
  16.     int min = 100;
  17.     int res = left;
  18.     for (int i = left; i <= right; i++)
  19.     {
  20.         int tmp = priority(exp[i]);
  21.         if (tmp <= min)
  22.         {
  23.             min = tmp;
  24.             res = i;
  25.         }
  26.     }
  27.     return res;
  28. }
  29.  
  30. struct Tree
  31. {
  32. private:
  33.     char op;
  34.     Tree *l, *r;
  35.  
  36. public:
  37.     Tree(string exp, int left, int right);
  38.     double calc();
  39.     void clear();
  40.     ~Tree();
  41. };
  42.  
  43. Tree::Tree(string exp, int left, int right)
  44. {
  45.     int last = last_op(exp, left, right);
  46.     this->op = exp[last];
  47.     if (isdigit(this->op))
  48.         return;
  49.     this->l = new Tree(exp, left, last - 1);
  50.     this->r = new Tree(exp, last + 1, right);
  51. }
  52.  
  53. double Tree::calc()
  54. {
  55.     double res = 0;
  56.     if (isdigit(this->op))
  57.         res = this->op - '0';
  58.     else
  59.     {
  60.         if (this->op == '+')
  61.             res = l->calc() + r->calc();
  62.         if (this->op == '-')
  63.             res = l->calc() - r->calc();
  64.         if (this->op == '*')
  65.             res = l->calc() * r->calc();
  66.         if (this->op == '/')
  67.             res = l->calc() / r->calc();
  68.     }
  69.     return res;
  70. }
  71.  
  72. void Tree::clear()
  73. {
  74.     if (isdigit(this->op))
  75.     {
  76.         delete this;
  77.         return;
  78.     }
  79.     l->clear();
  80.     r->clear();
  81.     delete this;
  82. }
  83.  
  84. Tree::~Tree() { this->clear(); }
  85.  
  86. int main()
  87. {
  88.     // 1 + 3 * 4 - 5 * 8 / 2 + 1 + 6 * 9 / 3
  89.     // 3 * 4 - 5 * 8
  90.     string exp;
  91.     getline(cin, exp);
  92.     Tree *t = new Tree(exp, 0, exp.size() - 1);
  93.     cout << t->calc() << '\n';
  94.     return 0;
  95. }
  96.  
RAW Paste Data