Created
May 21, 2025 20:44
-
-
Save primaryobjects/36db2ef755eb378c010b0c58a2f76b02 to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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