mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 18:34:42 +01:00
40: Champernowne's constant
This commit is contained in:
36
40_champ_constant/main.go
Normal file
36
40_champ_constant/main.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
p := 1
|
||||
for i := 0; i < 7; i++ {
|
||||
n := int(math.Pow(10, float64(i)))
|
||||
fmt.Println(n)
|
||||
p *= getDigit(n)
|
||||
}
|
||||
fmt.Println("num=", p)
|
||||
}
|
||||
|
||||
func getDigit(n int) int {
|
||||
var r, s, k int
|
||||
for s < n {
|
||||
r = s
|
||||
k++
|
||||
s += k * 9 * int(math.Pow(10, float64(k-1)))
|
||||
}
|
||||
h := n - r - 1
|
||||
t := int(math.Pow(10, float64(k-1))) + h/k
|
||||
p := h % k
|
||||
for i, s := range strconv.Itoa(t) {
|
||||
if i == p {
|
||||
ret, _ := strconv.Atoi(string(s))
|
||||
return ret
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
37
40_champ_constant/main_test.go
Normal file
37
40_champ_constant/main_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func Test_getDigit(t *testing.T) {
|
||||
type args struct {
|
||||
n int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"12",
|
||||
args{12},
|
||||
1,
|
||||
},
|
||||
{
|
||||
"13",
|
||||
args{13},
|
||||
1,
|
||||
},
|
||||
{
|
||||
"15",
|
||||
args{15},
|
||||
2,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := getDigit(tt.args.n); got != tt.want {
|
||||
t.Errorf("getDigit() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user