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

Evaluate Reverse Polish Notation

2014-02-26 09:30 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
class Solution {
public:
int evalRPN(vector<string> &tokens)
{
stack<int> st;
int len = tokens.size();
int i = 0;
int tem;
while(i<len)
{
if(!isdigit(tokens[i][0])&&tokens[i].length()==1)
{
switch(tokens[i][0])
{
case '+':
tem = st.top();
st.pop();
tem +=st.top();
st.top() = tem;
break;
case '-':
tem = st.top();
st.pop();
tem =st.top() - tem;
st.top() = tem;
break;
case '*':
tem = st.top();
st.pop();
tem *=st.top();
st.top() = tem;
break;
case '/':
tem = st.top();
st.pop();
tem =st.top()/tem;
st.top() = tem;
break;
default:
break;
}
}
else
{
tem = atoi(tokens[i].c_str());
st.push(tem);
}
i++;
}
return st.top();
}
};
说明:1. 字符串string str, 转化成c格式的操作:str.c_str();2. 字符串变整数,包括符号了, 负数也可以atoi(str.c_str());3.str可以当作数组操作

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