Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- We will keep a variable sum and add in sum one by one eg 1+21+(3+ -4)
- add 1 with 21 then with (3+ -4) ...
- sign will contain the sign of next upcoming integer(1,-1) eg. sign of full bracket is +
- but sign of 4 is -
- eg +- 9 so,sign of 9 is -
- Iterate through whole string:
- case 1:if currnt element is integer
- extract full integer eg. 789
- sign will have the sign for next integer ie. 789 so multiply element with sign
- now sign again will be +,so make sign =1.
- case 2:
- push current sum in stack and then sign of bracket also so that after finding sum of
- bracket we will multiply bracket sum with sign and add with sum.
- new sing for bracket will be positive so sign=1
- case 3:
- if closing bracket then we have solution of expression inside bracket in sum,
- so multiply sign of bracket which is top of stack with sum and add with
- actual sum which is in stack after sign.
- case 4:
- if current char = '-' means it will reverse sign in all cases
- '+','-' ='-'
- '-', '-'= '+'
- '+' sign will not impact previous sum.
- */
- class Solution:
- def calculate(self, s: str) -> int:
- prev_sign=1
- cur=0
- i=0
- st=[]
- total=0
- while i<len(s):
- if s[i]==' ':
- i+=1
- continue;
- num=0
- while i<len(s) and s[i].isdigit():
- num=num*10+int(s[i])
- i+=1
- total+=(prev_sign*num)
- if i>=len(s):
- break
- if s[i]=='-':
- prev_sign=-1
- i+=1
- elif s[i]=='+':
- prev_sign=1
- i+=1
- elif s[i]=='(':
- st.append(total)
- st.append(prev_sign)
- total=0
- prev_sign=1
- i+=1
- elif s[i]==')':
- prev_sign=st.pop()
- total=prev_sign*total+st.pop()
- i+=1
- return total
Advertisement
Add Comment
Please, Sign In to add comment