Leetcode: 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

int evalRPN(vector<string> &tokens) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(tokens.size()==1)return stoi(*tokens.begin());
        stack<int> numbers;
		vector<string>::iterator it = tokens.begin();
		int op1 = 0;
		int op2 = 0;
		while(it != tokens.end())
		{
			if(*it == "+"||*it == "-" || *it == "*" || *it == "/")
			{
				op2 = numbers.top();
				numbers.pop();
				op1 = numbers.top();
				numbers.pop();
				if(*it == "+")
					numbers.push(op1+op2);
				else if(*it == "-")
					numbers.push(op1-op2);
				else if(*it == "*")
					numbers.push(op1*op2);
				else
					numbers.push(op1/op2);
			}
			else
				numbers.push(stoi(*it));
			it++;
		}
		return numbers.top();
    }




你可能感兴趣的:(LeetCode,reverse,Polish,Notat)