150. Evaluate Reverse Polish Notation

This commit is contained in:
Пытков Роман
2024-01-31 00:49:39 +03:00
parent 1e43adf29e
commit 9d50f345d1
5 changed files with 84 additions and 5 deletions

View File

@@ -0,0 +1,31 @@
namespace _150._Evaluate_Reverse_Polish_Notation;
public class Solution
{
public int EvalRPN(string[] tokens)
{
var stack = new Stack<int>(tokens.Length);
foreach (var token in tokens)
{
if (int.TryParse(token, out var number))
stack.Push(number);
else
{
int right = stack.Pop();
int left = stack.Pop();
char op = token[0];
stack.Push(Calc(op, left, right));
}
}
return stack.Pop();
}
private int Calc(char op, int left, int right) => op switch
{
'+' => left + right,
'-' => left - right,
'*' => left * right,
'/' => left / right,
_ => throw new ArgumentOutOfRangeException()
};
}