mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 19:54:43 +01:00
16: power digit sum
This commit is contained in:
34
16_power_digit_sum/main.go
Normal file
34
16_power_digit_sum/main.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
n := &big.Int{}
|
||||||
|
n.SetInt64(1024)
|
||||||
|
p := (&big.Int{}).SetInt64(1)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
p = p.Mul(p, n)
|
||||||
|
}
|
||||||
|
sum, err := SumDigits(p.String())
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("product:", p.String(), "sum:", sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SumDigits(input string) (int, error) {
|
||||||
|
l := len(input)
|
||||||
|
sum := 0
|
||||||
|
for i := 0; i < l; i++ {
|
||||||
|
n, err := strconv.Atoi(input[i : i+1])
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("invalid input: %s", input)
|
||||||
|
}
|
||||||
|
sum += n
|
||||||
|
}
|
||||||
|
return sum, nil
|
||||||
|
}
|
||||||
60
16_power_digit_sum/power_digit_sum_test.go
Normal file
60
16_power_digit_sum/power_digit_sum_test.go
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSumDigits(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
want int
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"invalid",
|
||||||
|
"abc",
|
||||||
|
0,
|
||||||
|
fmt.Errorf("invalid input: %s", "abc"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"invalid_2",
|
||||||
|
"1a",
|
||||||
|
0,
|
||||||
|
fmt.Errorf("invalid input: %s", "1a"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"1",
|
||||||
|
"1",
|
||||||
|
1,
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"123",
|
||||||
|
"123",
|
||||||
|
6,
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"2345",
|
||||||
|
"2345",
|
||||||
|
14,
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got, err := SumDigits(tc.input)
|
||||||
|
if !reflect.DeepEqual(err, tc.wantErr) {
|
||||||
|
t.Errorf("SumDigits(%s) err=%v want err %v", tc.input, err, tc.wantErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("SumDigits(%s)=%d, want %d", tc.input, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user