Created
April 5, 2017 19:17
-
-
Save VojtaStavik/35ad31e37c3a34ee930685f9dbc36bf1 to your computer and use it in GitHub Desktop.
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
func calculateHammingDistance(x: Int, y: Int) -> Int { | |
// Step 1: Find different bits | |
let signedDifferentBits = x ^ y | |
// We bitcast Int to UInt to allow the algorithm work correctly also for negative numbers. | |
var differentBits: UInt = unsafeBitCast(signedDifferentBits, to: UInt.self) | |
// Step 2: Count them | |
var counter = 0 | |
// Until there are some bits set to '1' in differentBits. | |
while differentBits > 0 { | |
// Mask differentBits with number 1 aka 00000001. | |
// By doing this, we set all bits of differentBits | |
// but the last one to zero. | |
let maskedBits = differentBits & 1 | |
// If the last bit is not zero, | |
if maskedBits != 0 { | |
// increment the counter. | |
counter += 1 | |
} | |
// Shift bits in differentBits to the right. | |
differentBits = differentBits >> 1 | |
} | |
// We're done, return the number of 1s we've found. | |
return counter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment