imashutosh51

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

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