Skip to content

Instantly share code, notes, and snippets.

@hyukhur
Created November 9, 2017 08:01
Show Gist options
  • Save hyukhur/92edf6f43479e574ed09c6de56093449 to your computer and use it in GitHub Desktop.
Save hyukhur/92edf6f43479e574ed09c6de56093449 to your computer and use it in GitHub Desktop.
luhn check sum
func luhnCheckSum(number stringWithoutSpaces: String) -> Bool {
guard let _ = Int(stringWithoutSpaces) else { return false }
var even = 0
var sum = 0
for char in stringWithoutSpaces.reversed() {
guard let decimals = Int(String(char)) else { continue }
let added: Int = decimals * ( 1 << (even & 1) )
even = even + 1
sum = sum + added % 10 + added / 10
}
return sum % 10 == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment