Advertisement
imashutosh51

Basic calculator with +,-,(,) and unary operator

Aug 9th, 2022 (edited)
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1.  
  2. /*
  3. Logic:
  4. We will keep a variable sum and add in sum one by one eg 1+21+(3+ -4)
  5. add 1 with 21 then with (3+ -4) ...
  6.  
  7. sign will contain the sign of next upcoming integer(1,-1) eg. sign of full bracket is +
  8. but sign of 4 is -
  9. eg +- 9 so,sign of 9 is -
  10.  
  11. Iterate through whole string:
  12. case 1:if currnt element is integer
  13.    extract full integer eg. 789
  14.    sign will have the sign for next integer ie. 789 so multiply element with sign
  15.    now sign again will be +,so make sign =1.
  16. case 2:
  17.    push current sum in stack and then sign of bracket also so that after finding sum of
  18.    bracket we will multiply bracket sum with sign and add with sum.
  19.    new sing for bracket will be positive so sign=1
  20.  
  21. case 3:
  22.    if closing bracket then we have solution of expression inside bracket in sum,
  23.    so multiply sign of bracket which is top of stack with sum and add with
  24.    actual sum which is in stack after sign.
  25.    
  26. case 4:
  27.    if current char = '-' means it will reverse sign in all cases
  28.    '+','-' ='-'
  29.    '-', '-'= '+'
  30.    
  31.    '+' sign will not impact previous sum.
  32. */
  33. class Solution {
  34. public:
  35.     int calculate(string s) {
  36.         int sign=1;
  37.         int sum=0;
  38.         stack <int> st;
  39.         for(int i=0;i<s.size();i++){
  40.             if(isdigit(s[i])){
  41.                 int num=0;
  42.                 while(i<s.size() && isdigit(s[i])){
  43.                     num=num*10+(s[i]-'0');
  44.                     i++;
  45.                 }
  46.                 i--;
  47.                 num*=sign;
  48.                 sum+=num;
  49.                 continue;
  50.             }
  51.             else if(s[i]=='('){
  52.                 st.push(sum);
  53.                 st.push(sign);
  54.                 sum=0;
  55.                 sign=1;
  56.             }
  57.             else if(s[i]==')'){
  58.                 sum=sum*st.top();
  59.                 st.pop();
  60.                 sum+=st.top();
  61.                 st.pop();
  62.             }
  63.             else if(s[i]=='-') sign=-1;
  64.             else if(s[i]=='+') sign=1;
  65.         }
  66.         return sum;
  67.     }
  68. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement