Skip to content

Commit

Permalink
Go: Soultion for 150-Evaluate-Reverse-Polish-Notation.go
Browse files Browse the repository at this point in the history
  • Loading branch information
Rushi Panchariya committed Sep 29, 2022
1 parent 2d343f6 commit d82b49b
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions go/150-Evaluate-Reverse-Polish-Notation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
func evalRPN(tokens []string) int {
var stack []int
var a, b int
for _, c := range tokens {
switch c {
case "+":
a, b, stack = getAndPopLastOperand(stack)
stack = append(stack, (a + b))
case "-":
a, b, stack = getAndPopLastOperand(stack)
stack = append(stack, (a - b))
case "*":
a, b, stack = getAndPopLastOperand(stack)
stack = append(stack, (a * b))
case "/":
a, b, stack = getAndPopLastOperand(stack)
stack = append(stack, (a / b))
default:
i, _ := strconv.Atoi(c)
stack = append(stack, i)
}
}
return stack[0]
}

func getAndPopLastOperand(stack []int) (int, int, []int) {
a := stack[len(stack)-2]
b := stack[len(stack)-1]
stack = stack[:len(stack)-2]

return a, b, stack
}

0 comments on commit d82b49b

Please sign in to comment.