Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Precedence:
- *,/ ->Left to right as per in expression
- +,- ->Left to right as per in expression
- so,* and division should be handles first.
- so we will be handling first * and division so after resolving multiplication and division we are only
- having positive and negative numbers so we will store positive and negative numbers in stack and finally
- we will add all numbers.
- */
- class Solution {
- public:
- int calculate(string s) {
- int size= s.size(),i=0,ans=0;
- char prevOperator='+';
- stack<int> sta;
- while(i<size){
- if(s[i]==' '){ //if space then ignore the character
- i++;
- continue;
- }
- int num=0;
- while(isdigit(s[i])) //extracting the number
- num = num*10 + (s[i++]-'0');
- if(prevOperator=='+') //if current sign is positive then push number
- sta.push(num);
- else if(prevOperator=='-') //if sign is negative push -1*num
- sta.push(-num);
- else if(prevOperator=='*'){ //if multiply opertor then multiply current number
- int x=sta.top(); //with top of the stack
- sta.pop();
- sta.push(x*num);
- }
- else if(prevOperator=='/'){ //divide current num with top of the stack
- int x=sta.top();
- sta.pop();
- sta.push(x/num);
- }
- prevOperator=s[i++];
- }
- while(sta.size()){
- ans+=sta.top();
- sta.pop();
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement