-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
54 lines (45 loc) · 1.2 KB
/
Solution.cs
File metadata and controls
54 lines (45 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Solution
{
public int EvalRPN(string[] tokens)
{
Stack<int> stack = [];
HashSet<string> operators = ["+", "-", "*", "/"];
foreach (string token in tokens)
{
if (!operators.Contains(token))
{
stack.Push(ParseIntFast(token));
continue;
}
int a = stack.Pop();
int b = stack.Pop();
switch (token)
{
case "+":
stack.Push(b + a);
break;
case "-":
stack.Push(b - a);
break;
case "*":
stack.Push(b * a);
break;
case "/":
stack.Push(b / a);
break;
}
}
return stack.Pop();
}
private static int ParseIntFast(string input)
{
int sign = input[0] == '-' ? -1 : 1;
int result = 0;
for (int i = sign == -1 ? 1 : 0; i < input.Length; i++)
{
result *= 10;
result += input[i] - '0';
}
return sign == 1 ? result : -result;
}
}