Advertisement
lazar955

Untitled

Oct 24th, 2023
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.65 KB | None | 0 0
  1. func evalRPN(tokens []string) int {
  2.     stack:=[]int{}
  3.  
  4.     operators:= map[string]func(int,int) int {
  5.         "+": func (a,b int) int { return a + b},
  6.         "-": func(a, b int) int { return a - b },
  7.         "*": func(a, b int) int { return a * b },
  8.         "/": func(a, b int) int { return a / b },
  9.     }
  10.  
  11.     for _,token:= range tokens {
  12.         if calc,f:= operators[token]; f {
  13.             a,b:=stack[len(stack)-2],stack[len(stack)-1]
  14.             val:= calc(a,b)
  15.             stack = append(stack[:len(stack)-2], val)
  16.         }else {
  17.             num,_:= strconv.Atoi(token)
  18.             stack=append(stack,num)
  19.         }
  20.     }
  21.     return stack[0]
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement