Advertisement
fireLUFFY

BinarySearch_Stacks_WordMachine

Jul 13th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. //fireLUFFY
  2. //BinarySearch: Stacks->Word_Machine
  3.  
  4. ////////Solution//////////
  5.  
  6. int solve(vector<string>& ops) {
  7.     stack<int>s;
  8.     for(int i=0;i<ops.size();++i)
  9.     {
  10.         if(s.empty())
  11.         {
  12.             if((ops[i]=="DUP")||(ops[i]=="POP")||(ops[i]=="+")||(ops[i]=="-"))
  13.             return -1;
  14.             else
  15.             s.push(stoi(ops[i]));
  16.         }
  17.         else if(s.size()==1)
  18.         {
  19.             if((ops[i]=="+")||(ops[i]=="-"))
  20.             return -1;
  21.             else
  22.             {
  23.                 if(ops[i]=="DUP")
  24.                 {
  25.                     int val=s.top();
  26.                     s.push(val);
  27.                 }
  28.                 else if(ops[i]=="POP")
  29.                 s.pop();
  30.                 else
  31.                 {
  32.                     string c=ops[i];
  33.                     int val=stoi(c);
  34.                     s.push(val);
  35.                 }
  36.             }
  37.         }
  38.         else
  39.         {
  40.             if(ops[i]=="DUP")
  41.             {
  42.                 int val=s.top();
  43.                 s.push(val);
  44.             }
  45.             else if(ops[i]=="POP")
  46.             s.pop();
  47.             else if(ops[i]=="+")
  48.             {
  49.                 int val1=s.top();
  50.                 s.pop();
  51.                 int val2=s.top();
  52.                 s.pop();
  53.                 val1=(val1+val2);
  54.                 s.push(val1);
  55.             }
  56.             else if(ops[i]=="-")
  57.             {
  58.                 int val1=s.top();
  59.                 s.pop();
  60.                 int val2=s.top();
  61.                 s.pop();
  62.                 val1=(val1-val2);
  63.                 s.push(val1);
  64.             }
  65.             else
  66.             {
  67.                 string c=ops[i];
  68.                 int val=stoi(c);
  69.                 s.push(val);
  70.             }
  71.         }
  72.     }
  73.     return s.top();
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement