Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
Created October 25, 2019 11:53
Show Gist options
  • Save EmmanuelGuther/1ebe1bc2b00f7a540a93c3f7d62bf3e3 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/1ebe1bc2b00f7a540a93c3f7d62bf3e3 to your computer and use it in GitHub Desktop.
KOTLIN function to validate credit card numbers
class LuhnValidator {
fun isValid(cardNumber: String): Boolean {
var s1 = 0
var s2 = 0
val reverse = StringBuffer(cardNumber).reverse().toString()
for (i in reverse.indices) {
val digit = Character.digit(reverse[i], 10)
when {
i % 2 == 0 -> s1 += digit
else -> {
s2 += 2 * digit
when {
digit >= 5 -> s2 -= 9
}
}
}
}
return (s1 + s2) % 10 == 0
}
companion object {
private const val DECIMAL_BASE = 10
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment