package main
import (
"fmt"
"strconv"
)
func sum13(isbn string) (int, error) {
s := 0
w := 1
for _, v := range isbn {
n, err := strconv.Atoi(string(v))
if err != nil {
return -1, fmt.Errorf("Failed to convert ISBN-13 character to int: %s", string(v))
}
s += n * w
if w == 1 {
w = 3
} else {
w = 1
}
}
return s, nil
}
func validISBN13(isbn13 string) (string, error) {
if len(isbn13) != 12 && len(isbn13) != 13 {
return "", fmt.Errorf("A string of length 12 or 13 is required to calculate the ISBN-13 check digit. Provided was: %s", isbn13)
}
s, err := sum13(isbn13[:12])
if err != nil {
return "", err
}
d := 10 - (s % 10)
if d == 10 {
return "0", nil
}
return strconv.Itoa(d), nil
}
func main() {
str := "1112223339123"
_, err := validISBN13(str)
if err != nil {
fmt.Println("InValid")
} else {
fmt.Println("Valid")
}
}
Valid