思路:
先转逆波兰,再求值
package main
import (
"fmt"
"strconv"
"strings"
)
func mid2fix(s string) []string {
res := []string{}
exp := strings.Fields(s)
ss := []string{}
fmt.Println(exp)
for _, c := range exp {
_, err := strconv.Atoi(c)
// 是数字 结果直接加
if err == nil {
res = append(res, c)
} else {
// 不是数字
if len(ss) == 0 {
// 栈空直接入
ss = append(ss, c)
} else {
// 判断优先级是否低于栈顶
lst := ss[len(ss)-1]
if low_prio(c, lst) {
for len(ss) > 0 {
res = append(res, ss[len(ss)-1])
ss = ss[:len(ss)-1]
}
}
ss = append(ss, c)
}
}
}
for len(ss) > 0 {
res = append(res, ss[len(ss)-1])
ss = ss[:len(ss)-1]
}
return res
}
func low_prio(a, b string) bool {
if a == "*" || a == "/" {
return false
} else {
if b == "*" || b == "/" {
return true
} else {
return false
}
}
}
func calc_res(exp []string) int {
s := []int{}
for _, ex := range exp {
num, err := strconv.Atoi(ex)
if err == nil {
s = append(s, num)
} else {
a, b := s[len(s)-2], s[len(s)-1]
s = s[:len(s)-2]
s = append(s, op(a, b, ex))
}
}
return s[0]
}
func op(a, b int, c string) int {
if c == "*" {
return a * b
} else if c == "/" {
return a / b
} else if c == "+" {
return a + b
} else {
return a - b
}
}
func main() {
tt := "2 + 3 * 4 - 5 / 6"
exp := mid2fix(tt)
fmt.Println(exp)
res := calc_res(exp)
fmt.Println(res)
}
标签:return,exp,ss,res,len,else,Golang,计算,表达式
From: https://www.cnblogs.com/notomatoes/p/16631244.html