C++ AC code clear and concise


  • 1
    P
    class Solution {
        bool is_operator(string str){
            if(strcmp(str.c_str(), "+") == 0 || strcmp(str.c_str(), "-") == 0 || strcmp(str.c_str(), "*") == 0 || strcmp(str.c_str(), "/") == 0)
                return true;
            else
                return false;
        }
    public:
        int evalRPN(vector<string>& tokens) {
            int i = 0, n1 = 0, n2 = 0, res = 0;
            stack<int> num;
            for(i = 0; i < tokens.size(); i++){
                if(!is_operator(tokens[i]))
                    num.push(atoi(tokens[i].c_str()));
                else{
                    n2 = num.top(), num.pop();
                    n1 = num.top(), num.pop();
                    res = 0;
                    switch(tokens[i][0]){
                        case '+': res = n1 + n2; break;
                        case '-': res = n1 - n2; break;
                        case '*': res = n1 * n2; break;
                        case '/': if(n2 != 0) res = n1 / n2; break;
                    }
                    num.push(res);
                }
            }
            return num.top();
        }
    };

  • 2
    Q

    is_operator could be more concise.

    int evalRPN(vector<string>& tokens) {
        stack<int> stn;
        for(auto s:tokens) {
            if(s.size()>1 || isdigit(s[0])) stn.push(stoi(s));
            else {
                auto x2=stn.top(); stn.pop();
                auto x1=stn.top(); stn.pop();
                switch(s[0]) {
                    case '+': x1+=x2; break;
                    case '-': x1-=x2; break;
                    case '*': x1*=x2; break;
                    case '/': x1/=x2; break;
                }
                stn.push(x1);
            }
        }
        return stn.top();
    }

Log in to reply
 

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