Advertisement
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 {
- public:
- int calculate(string s) {
- int sign=1;
- int sum=0;
- stack <int> st;
- for(int i=0;i<s.size();i++){
- if(isdigit(s[i])){
- int num=0;
- while(i<s.size() && isdigit(s[i])){
- num=num*10+(s[i]-'0');
- i++;
- }
- i--;
- num*=sign;
- sum+=num;
- continue;
- }
- else if(s[i]=='('){
- st.push(sum);
- st.push(sign);
- sum=0;
- sign=1;
- }
- else if(s[i]==')'){
- sum=sum*st.top();
- st.pop();
- sum+=st.top();
- st.pop();
- }
- else if(s[i]=='-') sign=-1;
- else if(s[i]=='+') sign=1;
- }
- return sum;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement