Clean c++ solution, no tons of logic


  • 1
    Y

    I simply extract all the operators first and then extract all numbers by stringstream. Stack is used.

     int calculate(string s){
    stack<char> ops;
    vector<char> ops_all;
    
    stack<int> nums;
    
    int i = 0;
    
    while (i != s.length()){
    	if (!isdigit(s[i])) {
    		ops_all.push_back(s[i]);
    		s[i] = ' ';
    	}
    	++i;
    }
    
    	stringstream ss(s);
    	string num;
    
    	ss >> num;
    	nums.push(stoi(num));
    
    	for(auto c:ops_all){
    		if (c == '+' || c == '-') {
    			ops.push(c);
    			ss >> num;
    			nums.push(stoi(num));
    		}
    		if (c == '*') {
    			ss >> num;
    			int temp = nums.top() * stoi(num);
    			nums.pop();
    			nums.push(temp);
    		}
    		if (c == '/') {
    			ss >> num;
    			int temp = (int) (nums.top() / stoi(num));
    			nums.pop();
    			nums.push(temp);
    		}
    	}
    
    	int additive;
    	int res = 0;
    
    	while (!ops.empty()){
    		if (ops.top() == '-') res -= nums.top();			
    		if (ops.top() == '+') res += nums.top();
    		ops.pop();
    		nums.pop();
    	}
    		res += nums.top();
    
    		return res;
    

    }


Log in to reply
 

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