逆波兰计算器

一:思路分析

1574155612427

二:代码实现

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
public class PolandNotation
{
public List<string> getListString(string suff)
{
string[] split = suff.Split(' ');
List<string> list = new List<string>();
foreach (var item in split)
{
list.Add(item);
}
return list;
}
public int calculate(List<string> list)
{
Stack<string> stack = new Stack<string>();
foreach (var item in list)
{
Regex regExp = new Regex("^\\d+$");//匹配的是多位数

if (regExp.IsMatch(item))
{
//入栈
stack.Push(item);
}
else
{
int num2 = Convert.ToInt32(stack.Pop());
int num1 = Convert.ToInt32(stack.Pop());
int res = 0;
if (item=="+")
{
res = num1 + num2;
}
else if (item == "-")
{
res = num1 - num2;
}
else if (item == "*")
{
res = num1 * num2;
}
else if (item == "/")
{
res = num1 / num2;
}
else
{
throw new Exception("运算符有问题! ");
}
//把res入栈
stack.Push(""+res);
}
}

return Convert.ToInt32(stack.Pop());
}
}

三:源码地址

Github