c++ using stack


  • 0
    B
    class Solution {
    public:
        int calculate(string s) {
            stack<int> num;
            stack<char> op;
            int result=0;
            if(!s.length()) return result;
            
            for(int i=0;i<s.length();i++){
                
                if('0'<=s[i] && s[i]<='9') {
                    int n=s[i]-'0';
                    //number might has more than 1 digit  
                    while(i+1<s.length() && '0'<=s[i+1] && s[i+1]<='9'){
                        n*=10;
                        n+=(s[++i]-'0');
                    }
                    
                    num.push(n);
                    if(!op.empty() && (op.top()=='*' || op.top()=='/')){
                       
                        int a=num.top();
                        num.pop();
                        a=op.top()=='*' ? a*num.top() : num.top()/a;
                        
                        num.pop();
                        num.push(a);
                        op.pop();
                    }
                
                }
                
                else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/') op.push(s[i]);
                else continue;
                
            }
            //note to reverse the "+" "-"
            stack<int>num1;
            stack<char>op1;
            while(!op.empty()){
                op1.push(op.top());
                op.pop();
            }
            while(!num.empty()){
                num1.push(num.top());
                num.pop();
            }
            
            while(!op1.empty()){
                int a=num1.top();
                num1.pop();
                a= op1.top()=='+' ? a+num1.top() : a-num1.top();
                
                num1.pop();
                num1.push(a);
                op1.pop();
            }
            return num1.top();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.