-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPCCalc.cs
69 lines (68 loc) · 2.04 KB
/
RPCCalc.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
class Program
{
public static void Main(string[] args)
{
int res = SolveRpc(Console.ReadLine().Split(' '));
string sres = int.MinValue == res ? "INVALID" : res.ToString();
Console.WriteLine(sres);
}
public static int SolveRpc(string[] ops)
{
int result = 0;
var stack = new Stack<int>();
try
{
foreach (var op in ops)
{
int iop = 0;
if (int.TryParse(op, out iop))
{
stack.Push(iop);
}
else
{
int x1, x2, x3;
char cop = op[0];
switch (cop)
{
case '+':
x2 = stack.Pop();
x1 = stack.Pop();
stack.Push(x1 + x2);
break;
case '-':
x2 = stack.Pop();
x1 = stack.Pop();
stack.Push(x1 - x2);
break;
case '*':
x2 = stack.Pop();
x1 = stack.Pop();
stack.Push(x1 * x2);
break;
case '/':
x2 = stack.Pop();
x1 = stack.Pop();
stack.Push(x1 / x2);
break;
default:
throw new InvalidOperationException();
}
}
}
result = stack.Pop();
}
// If the stack is empty, we'll get this.
catch (InvalidOperationException)
{
result = int.MinValue;
}
if (stack.Count > 0)
{
result = int.MinValue;
}
return result;
}
}