Created
October 25, 2019 11:53
-
-
Save EmmanuelGuther/1ebe1bc2b00f7a540a93c3f7d62bf3e3 to your computer and use it in GitHub Desktop.
KOTLIN function to validate credit card numbers
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
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