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
思路:
逆波兰表达式,使用一个栈来计算。
代码:
1 int evalRPN(vector<string> &tokens) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int l = tokens.size(); 5 if(l == 0) 6 return 0; 7 stack<int> nums; 8 for(int i = 0; i < l; i++){ 9 string tmp = tokens[i]; 10 if(tmp == "+"){ 11 int num1 = nums.top(); 12 nums.pop(); 13 int num2 = nums.top(); 14 nums.pop(); 15 nums.push(num1 + num2); 16 } 17 else if(tmp == "-"){ 18 int num1 = nums.top(); 19 nums.pop(); 20 int num2 = nums.top(); 21 nums.pop(); 22 nums.push(num2 - num1); 23 } 24 else if(tmp == "*"){ 25 int num1 = nums.top(); 26 nums.pop(); 27 int num2 = nums.top(); 28 nums.pop(); 29 nums.push(num1 * num2); 30 } 31 else if(tmp == "/"){ 32 int num1 = nums.top(); 33 nums.pop(); 34 int num2 = nums.top(); 35 nums.pop(); 36 nums.push(num2 / num1); 37 } 38 else 39 nums.push(atoi(tmp.c_str())); 40 } 41 return nums.top(); 42 }