-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
38 lines (37 loc) · 1.18 KB
/
Program.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
//按照逆波兰表达式定义做就好
using System;
using System.Collections.Generic;
namespace EvaluateReversePolishNotation
{
class Program
{
static void Main(string[] args)
{
string[] tokens = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" };
Console.WriteLine(EvalRPN(tokens));
}
static int EvalRPN(string[] tokens)
{
var stack = new Stack<int>();
foreach (var token in tokens)
{
if(token != "+" && token != "-" && token != "*" && token != "/")
stack.Push(int.Parse(token));
else
{
int num1 = stack.Pop();
int num2 = stack.Pop();
if(token == "+")
stack.Push(num2 + num1);
else if (token == "-")
stack.Push(num2 - num1);
else if (token == "*")
stack.Push(num2 * num1);
else
stack.Push(num2 / num1);
}
}
return stack.Peek();
}
}
}