24: pandigital products

This commit is contained in:
VicRen
2020-11-02 11:03:20 +08:00
parent 15d7363769
commit e49c04c8b9
4 changed files with 123 additions and 46 deletions

View File

@@ -0,0 +1,40 @@
package main
import (
"fmt"
"sort"
"strconv"
)
func main() {
sum := 0
for i := 0; i < 10000; i++ {
if hasPandigitalProduct(i) {
sum += i
}
}
fmt.Println("sum:", sum)
}
func hasPandigitalProduct(n int) bool {
for i := 1; i <= n; i++ {
for n%i == 0 && isPandigital(strconv.Itoa(n)+strconv.Itoa(i)+strconv.Itoa(n/i)) {
fmt.Printf("Pandigital:%d = %d * %d\n", n, i, n/i)
return true
}
}
return false
}
func isPandigital(s string) bool {
var ss []string
for _, c := range s {
ss = append(ss, string(c))
}
sort.Strings(ss)
s = ""
for _, c := range ss {
s += c
}
return s == "123456789"
}

View File

@@ -0,0 +1,63 @@
package main
import (
"testing"
)
func Test_isPandigital(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want bool
}{
{
"912345678",
args{"912345678"},
true,
},
{
"12345678",
args{"12345678"},
false,
},
{
"812349756",
args{"812349756"},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isPandigital(tt.args.s); got != tt.want {
t.Errorf("isPandigital() = %v, want %v", got, tt.want)
}
})
}
}
func Test_hasPandigitalProduct(t *testing.T) {
type args struct {
n int
}
tests := []struct {
name string
args args
want bool
}{
{
"7254",
args{7254},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := hasPandigitalProduct(tt.args.n); got != tt.want {
t.Errorf("hasPandigitalProduct() = %v, want %v", got, tt.want)
}
})
}
}