Created
March 4, 2022 14:20
-
-
Save CollinShoop/fa36a11d5a38cd9f1637b2749f4ffb9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func evalRPN(tokens []string) int { | |
nums := []int{} | |
push := func(n int) { | |
nums = append(nums, n) | |
} | |
pop := func() int { | |
n := nums[len(nums)-1] | |
nums = nums[:len(nums)-1] | |
return n | |
} | |
for _, token := range tokens { | |
switch token { | |
case "*": push(pop() * pop()) | |
case "/": | |
tmp := pop(); | |
push(pop() / tmp) | |
case "-": | |
tmp := pop(); | |
push(pop() - tmp) | |
case "+": push(pop() + pop()) | |
default: | |
n, _ := strconv.Atoi(token) | |
push(n) | |
} | |
} | |
return pop() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment