C++ solution using recursion


  • 1
    J
    class Solution {
    public:
        int calculate(string s) {
            s.insert(s.begin(), '(');
    		s.append(1,')');
    		int pos = 0;
    		return compute(s, pos);
    		
        }
    	int compute(string& s, int& pos)
    	{
    		int res = 0;
    		int num=0;
    		char op ='+';
    		
            for(int i=pos; i<s.size(); ++i)
    		{
    			pos++;
    			char ch = s[i];
    			if(isdigit(ch))
    			{
    				num = num * 10 + ch -'0';
    			}
    			else if(ch =='+' || ch == '-')
    			{
    				if(op =='+')
    					res += num;
    				else if(op =='-')
    					res -= num;
    				op = ch;
    				num=0;
    			}
    			else if(ch=='(')
    			{
    				if(op =='+')
    					res += compute(s, pos);
    				else if(op =='-')
    					res -= compute(s, pos);
    				i=pos-1;
    			}
    			else if(ch ==')')
    			{
    				if(op =='+')
    					res += num;
    				else if(op =='-')
    					res -= num;
    				return res;
    			}
    		}
    		return res;
    	}
    };

Log in to reply
 

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