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/work20.go

57 lines
1.4 KiB

5 months ago
package cap3
func Work20(callback func(x, y, z int)) {
// 检查x, y, z是否包含1到9的所有数字各一次,且不包含0
checkDigit := func(x, y, z int) bool {
appearCnt := make([]int, 10) // 创建一个数组来存储数字0-9的出现次数
// x的各位数字
appearCnt[x/10]++
appearCnt[x%10]++
// y的各位数字
appearCnt[y%10]++
appearCnt[y/10%10]++
appearCnt[y/100]++
// z的各位数字
appearCnt[z%10]++
appearCnt[z/10%10]++
appearCnt[z/100%10]++
appearCnt[z/1000]++
// 有0,不符合条件
if appearCnt[0] != 0 {
return false
}
// 检查1-9出现次数
for _, cnt := range appearCnt {
if cnt != 1 {
return false
}
}
return true
}
// 双重循环遍历所有可能的x和y组合
// x从12开始到98
for x := 12; x < 99; x++ {
// y从123开始到986
for y := 123; y < 987; y++ {
// 如果乘积超过9999,停止内层循环(太大了,已经不符合条件了)
z := x * y
if z > 9999 {
break
}
// 检查x, y, z各位数字情况
if checkDigit(x, y, z) {
// 回调结果
callback(x, y, z)
}
}
}
}