The Go language USES the Luhn algorithm to verify whether the credit card number is valid or not

  • 2020-05-27 05:48:36
  • OfStack

In this paper, an example is given to verify the validity of credit card number in Go via Luhn algorithm. Share with you for your reference. The specific implementation method is as follows:


package main
import (
    "fmt"
    "strings"
)
const input = `49927398716
49927398717
1234567812345678
1234567812345670`
var t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}
func luhn(s string) bool {
    odd := len(s) & 1
    var sum int
    for i, c := range s {
        if c < '0' || c > '9' {
            return false
        }
        if i&1 == odd {
            sum += t[c-'0']
        } else {
            sum += int(c - '0')
        }
    }
    return sum%10 == 0
}
func main() {
    for _, s := range strings.Split(input, "\n") {
        fmt.Println(s, luhn(s))
    }
}

The output

49927398716 true
49927398717 false
1234567812345678 false
1234567812345670 true

I hope this article has been helpful to you in the programming of Go language.


Related articles: