Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created May 21, 2025 20:44
Show Gist options
  • Save primaryobjects/36db2ef755eb378c010b0c58a2f76b02 to your computer and use it in GitHub Desktop.
Save primaryobjects/36db2ef755eb378c010b0c58a2f76b02 to your computer and use it in GitHub Desktop.
public class Solution {
public int EvalRPN(string[] tokens) {
char[] operators = { '+', '-', '*', '/' };
Stack<int> operands = new Stack<int>();
foreach (string token in tokens)
{
bool isOperator = token.Length == 1 && token.IndexOfAny(operators) != -1;
if (!isOperator)
{
operands.Push(Convert.ToInt32(token));
}
else
{
int result = 0;
int b = operands.Pop();
int a = operands.Pop();
switch (token[0]) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = a / b; break;
}
operands.Push(result);
Console.WriteLine($"{a} {token} {b} = {result}");
}
}
return operands.Pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment