Skip to content

Instantly share code, notes, and snippets.

@jlcarrascof
Last active October 6, 2023 13:14
Show Gist options
  • Save jlcarrascof/b7502a152ec2c10fbbded6e3d2f134fe to your computer and use it in GitHub Desktop.
Save jlcarrascof/b7502a152ec2c10fbbded6e3d2f134fe to your computer and use it in GitHub Desktop.
Bit Counting
# Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
# Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
def count_bits(n)
count = 0
while n > 0
count += n & 1
n >>= 1
end
return count
end
puts count_bits(1234)
# Output: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment