[leetcode] Evaluate Reverse Polish Notation

来源:互联网 发布:淘宝客佣金代扣款给谁 编辑:程序博客网 时间:2024/06/05 11:55

From : https://leetcode.com/problems/evaluate-reverse-polish-notation/

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution {public:    int resolve(string s) {        int num=0, size=s.size(), flag=1;        for(int i=0; i<size; i++) {            if(s[i]=='-') flag=-1;            if(s[i]>='0' && s[i]<='9') {                num = num*10 + s[i]-'0';            }        }        return flag*num;    }    int evalRPN(vector<string>& tokens) {        string cur;        stack<int> nums;        int size=tokens.size();        for(int i=0; i<size; i++) {            cur = tokens[i];            if(cur=="+" || cur=="-" || cur=="*" || cur=="/") { ////b . a                int a = nums.top();                nums.pop();                int b = nums.top();                nums.pop();                if(cur == "+") {                    nums.push(b+a);                } else if(cur == "-") {                    nums.push(b-a);                } else if(cur == "*") {                    nums.push(b*a);                } else /*if(a!=0)*/{                    nums.push(b/a);                }            } else {                nums.push(resolve(cur));            }        }        return nums.top();    }};


0 0
原创粉丝点击