如果是数字,则压入栈;若为符号,则取出数字进行操作后入栈。
public class Solution {
public int EvalRPN(string[] tokens) {
Stack<int> s = new Stack<int>();
int i = 0;
while(i<tokens.Length)
{
int tmp = 0;
if(int.TryParse(tokens[i], out tmp))
{
s.Push(tmp);
}
else
{
var v2 = s.Pop();
var v1 = s.Pop();
if(tokens[i] == "+")
{
s.Push(v1+v2);
}
else if(tokens[i] == "/"){
s.Push(v1/v2);
}
else if(tokens[i] == "-")
{
s.Push(v1-v2);
}
else if(tokens[i] == "*")
{
s.Push(v1*v2);
}
}
i++;
}
return s.Pop();
}
}
public class Solution {
public int EvalRPN(string[] tokens)
{
Stack<int> stack = new Stack<int>();
int sum;
int tmp;
int i = 0;
int v1, v2;
while(i < tokens.Length)
{
tmp = 0;
if(int.TryParse(tokens[i], out tmp))
{
stack.Push(tmp);
}
else
{
v2 = stack.Pop();
v1 = stack.Pop();
switch(tokens[i])
{
case "+":
stack.Push(v1 + v2);
break;
case "-":
stack.Push(v1 - v2);
break;
case "*":
stack.Push(v1 * v2);
break;
case "/":
stack.Push(v1 / v2);
break;
}
}
i++;
}
return stack.Peek();
}
}