Skip to content

Commit be7bb93

Browse files
committed
evaluate_reverse_polish_notation
1 parent a1db0fa commit be7bb93

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
133133
#### [147. insertion sort list](https://github.com/hitzzc/go-leetcode/tree/master/insertion_sort_list)
134134
#### [148. sort list](https://github.com/hitzzc/go-leetcode/tree/master/sort_list)
135135
#### [149. Max Points on a Line](https://github.com/hitzzc/go-leetcode/tree/master/max_points_on_a_line)
136+
#### [150. evaluate reverse polish notation](https://github.com/hitzzc/go-leetcode/tree/master/evaluate_reverse_polish_notation)
136137

137138

138139

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package evaluate_reverse_polish_notation
2+
3+
import (
4+
"strconv"
5+
)
6+
7+
func evalRPN(tokens []string) int {
8+
cache := []int{}
9+
var num1, num2, num int
10+
for i := range tokens {
11+
if tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/" {
12+
num2 = cache[len(cache)-1]
13+
num1 = cache[len(cache)-2]
14+
cache[len(cache)-2] = calculate(num1, num2, tokens[i])
15+
cache = cache[:len(cache)-1]
16+
} else {
17+
num, _ = strconv.Atoi(tokens[i])
18+
cache = append(cache, num)
19+
}
20+
}
21+
return cache[0]
22+
}
23+
24+
func calculate(num1, num2 int, op string) int {
25+
if op == "+" {
26+
return num1 + num2
27+
}
28+
if op == "-" {
29+
return num1 - num2
30+
}
31+
if op == "*" {
32+
return num1 * num2
33+
}
34+
if op == "/" {
35+
return num1 / num2
36+
}
37+
return 0
38+
}

0 commit comments

Comments
 (0)