You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
lavos/cap3/ex34.go

71 lines
2.2 KiB

package cap3
import "fmt"
const (
_opAdd = '+' // 加
_opMinus = '-' // 减
_opMulti = '*' // 乘
_opDiv = '/' // 除
)
var allOperations = [4]byte{_opAdd, _opMinus, _opMulti, _opDiv}
func Ex34(x1, x2, x3, x4, x5, y int) []string {
result := make([]string, 0)
operations := make([]byte, 4)
nums := [5]int{x1, x2, x3, x4, x5}
// 一层一层尝试运算符
for _, operations[0] = range allOperations {
// 当前为除法,判断下一个数是否为0,如果是则直接跳过,下同
if operations[0] == _opDiv && nums[1] == 0 {
continue
}
for _, operations[1] = range allOperations {
if operations[1] == _opDiv && nums[2] == 0 {
continue
}
for _, operations[2] = range allOperations {
if operations[2] == _opDiv && nums[3] == 0 {
continue
}
for _, operations[4] = range allOperations {
if operations[4] == _opDiv && nums[4] == 0 {
continue
}
// 计算表达式
p, f, q := 0, 1, nums[1]
for i, op := range operations {
switch op {
case _opAdd:
p += f * q
f, q = 1, nums[i+1]
case _opMinus:
p += f * q
f, q = -1, nums[i+1]
case _opMulti:
q *= nums[i+1]
case _opDiv:
q /= nums[i+1]
}
}
// 结果等于给定的数字y,添加到结果集中
if p+f*q == y {
text := ""
for _, num := range nums {
text += fmt.Sprintf("%d %c ", num, operations)
}
text += fmt.Sprintf("%d = %d\n", nums[4], y)
result = append(result, text)
}
}
}
}
}
return result
}