您的位置:首页 > 编程语言 > Lua

Leetcode: Evaluate Reverse Polish Notation

2014-01-03 19:39 369 查看
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) {
stack<int> operands;
operands.push(0);
int operand1, operand2;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+") {
getOperands(operands, operand1, operand2);
operands.push(operand1 + operand2);
}
else if (tokens[i] == "-") {
getOperands(operands, operand1, operand2);
operands.push(operand1 - operand2);
}
else if (tokens[i] == "*") {
getOperands(operands, operand1, operand2);
operands.push(operand1 * operand2);
}
else if (tokens[i] == "/") {
getOperands(operands, operand1, operand2);
operands.push(operand1 / operand2);
}
else {
operands.push(atoi(tokens[i].c_str()));
}
}

return operands.top();
}

void getOperands(stack<int> &operands, int &op1, int &op2) {
op2 = operands.top();
operands.pop();
op1 = operands.top();
operands.pop();
}
};


====================第二次============================
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> operands;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int op2 = operands.top();
operands.pop();
int op1 = operands.top();
operands.pop();
operands.push(eval(tokens[i][0], op1, op2));
}
else {
operands.push(atoi(tokens[i].c_str()));
}
}

return operands.top();
}

int eval(char action, int op1, int op2) {
int result = 0;
switch (action) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode