Merge pull request #143 from novahe/fix/150

clean up redundant code
This commit is contained in:
halfrost
2021-06-01 13:08:48 +08:00
committed by GitHub
2 changed files with 34 additions and 80 deletions

View File

@ -5,46 +5,23 @@ import (
) )
func evalRPN(tokens []string) int { func evalRPN(tokens []string) int {
if len(tokens) == 1 { stack := make([]int, 0, len(tokens))
i, _ := strconv.Atoi(tokens[0]) for _, token := range tokens {
return i v, err := strconv.Atoi(token)
} if err == nil {
stack, top := []int{}, 0 stack = append(stack, v)
for _, v := range tokens { } else {
switch v { num1, num2 := stack[len(stack)-2], stack[len(stack)-1]
stack = stack[:len(stack)-2]
switch token {
case "+": case "+":
{ stack = append(stack, num1+num2)
sum := stack[top-2] + stack[top-1]
stack = stack[:top-2]
stack = append(stack, sum)
top--
}
case "-": case "-":
{ stack = append(stack, num1-num2)
sub := stack[top-2] - stack[top-1]
stack = stack[:top-2]
stack = append(stack, sub)
top--
}
case "*": case "*":
{ stack = append(stack, num1*num2)
mul := stack[top-2] * stack[top-1]
stack = stack[:top-2]
stack = append(stack, mul)
top--
}
case "/": case "/":
{ stack = append(stack, num1/num2)
div := stack[top-2] / stack[top-1]
stack = stack[:top-2]
stack = append(stack, div)
top--
}
default:
{
i, _ := strconv.Atoi(v)
stack = append(stack, i)
top++
} }
} }
} }

View File

@ -66,46 +66,23 @@ import (
) )
func evalRPN(tokens []string) int { func evalRPN(tokens []string) int {
if len(tokens) == 1 { stack := make([]int, 0, len(tokens))
i, _ := strconv.Atoi(tokens[0]) for _, token := range tokens {
return i v, err := strconv.Atoi(token)
} if err == nil {
stack, top := []int{}, 0 stack = append(stack, v)
for _, v := range tokens { } else {
switch v { num1, num2 := stack[len(stack)-2], stack[len(stack)-1]
stack = stack[:len(stack)-2]
switch token {
case "+": case "+":
{ stack = append(stack, num1+num2)
sum := stack[top-2] + stack[top-1]
stack = stack[:top-2]
stack = append(stack, sum)
top--
}
case "-": case "-":
{ stack = append(stack, num1-num2)
sub := stack[top-2] - stack[top-1]
stack = stack[:top-2]
stack = append(stack, sub)
top--
}
case "*": case "*":
{ stack = append(stack, num1*num2)
mul := stack[top-2] * stack[top-1]
stack = stack[:top-2]
stack = append(stack, mul)
top--
}
case "/": case "/":
{ stack = append(stack, num1/num2)
div := stack[top-2] / stack[top-1]
stack = stack[:top-2]
stack = append(stack, div)
top--
}
default:
{
i, _ := strconv.Atoi(v)
stack = append(stack, i)
top++
} }
} }
} }