Use RPN(Reverse Polish Notation) to implement calculator

Last updated on January 25, 2023 pm

RPN(Reverse Polish Notation): Operators follow their operands, in contrast to PN(Polish Notation).

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
public class ReversePolishNotation {
public static void main(String[] args) {
// (3+4)*5-6 --> 3 4 + 5 * 6 -
String suffixNotation = "3 4 + 5 * 6 -";

// get string list
List<String> rpnList = getListString(suffixNotation);

// test
int result = calculate(rpnList);
System.out.println(result);

}

public static List<String> getListString(String suffixNotaion) {
String[] split = suffixNotaion.split(" ");
List<String> list = new ArrayList<String>();
for (String element : split) {
list.add(element);
}
return list;
}

// RPN: from left to right
public static int calculate(List<String> list) {
//only need one stack
Stack<String> strings = new Stack<>();
for (String s : list) {
//regex
if (s.matches("\\d+")) {//multi-number
//push in numbers
strings.push(s);
} else { //when it comes to operator
//calculate 2 numbers, then push in the result
int num2 = Integer.parseInt(strings.pop());
int num1 = Integer.parseInt(strings.pop());
int result = 0;
switch (s) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "%":
result = num1 / num2;
break;
default:
throw new RuntimeException("There's something wrong with the operator.");
}
strings.push(String.valueOf(result));
}
}
return Integer.parseInt(strings.pop());
}
}

Use RPN(Reverse Polish Notation) to implement calculator
http://hihiko.zxy/2023/01/25/Use-RPN-Reverse-Polish-Notation-to-implement-calculator/
Author
Posted on
January 25, 2023
Licensed under