Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@swarut
Created February 12, 2015 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swarut/501557b6834413d163e7 to your computer and use it in GitHub Desktop.
Save swarut/501557b6834413d163e7 to your computer and use it in GitHub Desktop.
nbit
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