Advertisement
imashutosh51

basic calculator II

Oct 18th, 2022
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. /*
  2. Precedence:
  3. *,/ ->Left to right as per in expression
  4. +,- ->Left to right as per in expression
  5.  
  6. so,* and division should be handles first.
  7. so we will be handling first * and division so after resolving multiplication and division we are only
  8. having positive and negative numbers so we will store positive and negative numbers in stack and finally
  9. we will add all numbers.
  10. */
  11. class Solution {
  12. public:
  13.     int calculate(string s) {
  14.         int size= s.size(),i=0,ans=0;
  15.         char prevOperator='+';
  16.         stack<int> sta;
  17.         while(i<size){
  18.             if(s[i]==' '){   //if space then ignore the character
  19.                 i++;
  20.                 continue;
  21.             }
  22.             int num=0;
  23.             while(isdigit(s[i]))   //extracting the number
  24.                 num = num*10 + (s[i++]-'0');
  25.             if(prevOperator=='+')   //if current sign is positive then push number
  26.                 sta.push(num);
  27.             else if(prevOperator=='-') //if sign is negative push -1*num
  28.                 sta.push(-num);
  29.             else if(prevOperator=='*'){  //if multiply opertor then multiply current number
  30.                 int x=sta.top();         //with top of the stack
  31.                 sta.pop();
  32.                 sta.push(x*num);
  33.             }
  34.             else if(prevOperator=='/'){  //divide current num with top of the stack
  35.                 int x=sta.top();
  36.                 sta.pop();
  37.                 sta.push(x/num);
  38.             }
  39.             prevOperator=s[i++];
  40.         }
  41.         while(sta.size()){
  42.             ans+=sta.top();
  43.             sta.pop();
  44.         }
  45.         return ans;
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement