Total Accepted: 55722 Total Submissions: 249668 Difficulty: Medium
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 evalRPN(vector<string>& tokens) { int tokens_size = tokens.size(); int i=0,k=0; long long int num1 =0,num2=0; while(i<tokens_size){ if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" ||tokens[i]=="/"){ num2 = stoi(tokens[--k]); num1 = stoi(tokens[--k]); switch(tokens[i][0]){ case '+': num1+=num2;break; case '-': num1-=num2;break; case '*': num1*=num2;break; case '/': num1/=num2;break; } tokens[k++] = to_string(num1); i++; }else{ tokens[k++]=tokens[i++]; } } return stoi(tokens[0]); } };