Evaluate Reverse Polish Notation

int evalRPN(vector<string>& tokens) {
        stack<int> s;
        int i=0;
        int result=0;
        while(i<tokens.size())
        {
            string n=tokens[i];
            if(n=="+"||n=="-"||n=="*"||n=="/")
            {
                int x2=s.top();
                s.pop();
                int x1=s.top();
                s.pop();
                if(n=="+")
                {
                    result=x1+x2;
                    s.push(result);
                }
                else if(n=="-")
                {
                    result=x1-x2;
                    s.push(result);
                }
                else if(n=="*")
                {
                    result=x1*x2;
                    s.push(result);
                }
                else
                {
                    result=x1/x2;
                    s.push(result);
                }
                    
            }
            else
                s.push(stoi(n));
            i++;
        }
        return s.top();
        
    }

一开始的时候,我return的是result,但是在leetcode上有一个测试用例无法通过,那就是当只输入一个常量而不进行运算的时候,比如[“18”]。这种情况下应该输出18,而return result则返回0。

 

posted on 2016-04-10 10:22  summerkiki  阅读(136)  评论(0编辑  收藏  举报