Created
February 12, 2015 16:27
-
-
Save swarut/501557b6834413d163e7 to your computer and use it in GitHub Desktop.
nbit
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
def nbit(n1, n2) | |
bits1, bits2 = n1.to_s(2), n2.to_s(2) | |
bits1, bits2 = bits1.length > bits2.length ? | |
[bits1, bits2.rjust(bits1.length, "0")] : | |
[bits2, bits1.rjust(bits2.length, "0")] | |
result = bits1.split("").inject([0, bits2.split("")]) do |acc, bit| | |
tmp = acc[1].shift | |
acc[0] += tmp == bit ? 0 : 1 | |
[acc[0], acc[1]] | |
end | |
result[0] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment