aboutsummaryrefslogtreecommitdiffstats
path: root/150/main.go
blob: 19531344080fe114f04e0a72dc79fc841d71b227 (plain) (blame)
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
package main

import (
	"fmt"
	"strconv"

	"github.com/emirpasic/gods/stacks/arraystack"
)

func evalRPN(tokens []string) int {
	st := arraystack.New()
	for _, op := range tokens {
		switch op {
		case "+":
			{
				val1, _ := st.Pop()
				val2, _ := st.Pop()
				res := val1.(int) + val2.(int)
				fmt.Printf("%d + %d = %d\n", val1, val2, res)
				st.Push(res)
			}
		case "-":
			{
				val1, _ := st.Pop()
				val2, _ := st.Pop()
				res := val2.(int) - val1.(int)
				fmt.Printf("%d - %d = %d\n", val2, val1, res)
				st.Push(res)
			}
		case "*":
			{
				val1, _ := st.Pop()
				val2, _ := st.Pop()
				res := val1.(int) * val2.(int)
				fmt.Printf("%d * %d = %d\n", val1, val2, res)
				st.Push(res)
			}
		case "/":
			{
				val1, _ := st.Pop()
				val2, _ := st.Pop()
				res := val2.(int) / val1.(int)
				fmt.Printf("%d / %d = %d\n", val2, val1, res)
				st.Push(res)
			}
		default:
			{
				val1, _ := strconv.Atoi(op)
				st.Push(val1)
			}
		}
	}

	final, _ := st.Pop()

	return final.(int)
}

func main() {
	fmt.Println(evalRPN([]string{"2", "1", "+", "3", "*"}))
	fmt.Println(evalRPN([]string{"4", "13", "5", "/", "+"}))
	fmt.Println(evalRPN([]string{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}))
}