Created
July 8, 2019 16:12
-
-
Save davidglezz/186b4d834f34c76fe15045037e5199cc to your computer and use it in GitHub Desktop.
IsValidEan13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IsValidEan13 return true if given ean13 number is valid | |
func IsValidEan13(code string) bool { | |
if len(code) != 13 { | |
return false | |
} | |
oddSum := 0 | |
evenSum := 0 | |
for i, n := range code[:12] { | |
digit := int(n - '0') | |
if digit < 0 || 9 < digit { | |
return false | |
} | |
if i%2 == 0 { | |
evenSum += digit | |
} else { | |
oddSum += digit | |
} | |
} | |
checksum := 10 - (oddSum*3+evenSum)%10 | |
if checksum == 10 { | |
checksum = 0 | |
} | |
return checksum == int(code[12]-'0') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment