Advertisement
Guest User

reversePolishCalc

a guest
Feb 27th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. int calculateReversePolishNotation(const string reversePolishNotation) // 1 2+ 2 3+* 2^
  2. {
  3.     StackArray<int>* calculators = new StackArray<int>;
  4.     int tempResult = 0;
  5.    
  6.     for (int i = 0; i < reversePolishNotation.length(); i++)
  7.     {
  8.         switch (reversePolishNotation[i])
  9.         {
  10.             case '+':
  11.             {
  12.                 tempResult = calculators->pop() + calculators->pop();
  13.                 calculators->push(tempResult);
  14.                 break;
  15.             }
  16.             case '-':
  17.             {
  18.                 int rightOperand = calculators->pop();
  19.                 int leftOperand = calculators->pop();
  20.                 tempResult = leftOperand - rightOperand;
  21.                 calculators->push(tempResult);
  22.                 break;
  23.             }
  24.             case '*':
  25.             {
  26.                 tempResult = calculators->pop() * calculators->pop();
  27.                 calculators->push(tempResult);
  28.                 break;
  29.             }
  30.             case '/':
  31.             {
  32.                 int rightOperand = calculators->pop();
  33.                 int leftOperand = calculators->pop();
  34.                 tempResult = leftOperand / rightOperand;
  35.                 calculators->push(tempResult);
  36.                 break;
  37.             }
  38.             case '^':
  39.             {
  40.                 int rightOperand = calculators->pop();
  41.                 int leftOperand = calculators->pop();
  42.                 tempResult = pow(leftOperand, rightOperand);
  43.                 calculators->push(tempResult);
  44.                 break;
  45.             }
  46.             default:
  47.             {
  48.                 //cout << reversePolishNotation[i] << '\n';
  49.                 //cout << reversePolishNotation[i] - '0';
  50.                 calculators->push((reversePolishNotation[i] - '0'));
  51.                 break;
  52.             }
  53.         }
  54.     }
  55.     return calculators->pop();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement