150. Evaluate Reverse Polish Notation
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>_150._Evaluate_Reverse_Polish_Notation</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
11
150. Evaluate Reverse Polish Notation/Program.cs
Normal file
11
150. Evaluate Reverse Polish Notation/Program.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
|
||||
using _150._Evaluate_Reverse_Polish_Notation;
|
||||
|
||||
string[] arr = ["10", "1", "1", "2", "+", "+", "+"];
|
||||
var sol = new Solution();
|
||||
int n = 100000;
|
||||
while(n-- > 0)
|
||||
Console.WriteLine(sol.EvalRPN(["10", "1", "1", "2", "+", "+", "+"]));
|
||||
|
||||
|
||||
31
150. Evaluate Reverse Polish Notation/Solution.cs
Normal file
31
150. Evaluate Reverse Polish Notation/Solution.cs
Normal 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()
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user