您的位置:首页 > 编程语言 > C语言/C++

leetcode #150 in cpp

2016-06-28 11:15 405 查看
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


Code:

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
int res;
int a,b;
for(int i = 0; i < tokens.size(); i ++){
string temp = tokens[i];
if(temp == "*"){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(a*b);
}else if(temp == "/"){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(b/a);
}else if(temp == "+"){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(a+b);
}else if(temp == "-"){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(b-a);
}else{
stk.push(stoi(temp));
}
}
return stk.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode