Created
November 9, 2017 08:01
-
-
Save hyukhur/92edf6f43479e574ed09c6de56093449 to your computer and use it in GitHub Desktop.
luhn check sum
This file contains hidden or 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
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