mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-29 22:24:07 +01:00
25 lines
362 B
Ruby
25 lines
362 B
Ruby
def binary_count_setbits(x)
|
|
raise 'Input must be a positive integer' if x < 0
|
|
|
|
binary = x.to_s(2)
|
|
|
|
binary.chars.map { |c| c.to_i }.reduce(:+)
|
|
end
|
|
|
|
begin
|
|
binary_count_setbits(-1)
|
|
rescue => e
|
|
puts e.message
|
|
end
|
|
|
|
puts binary_count_setbits(0)
|
|
# 0
|
|
|
|
puts binary_count_setbits(1)
|
|
# 1
|
|
|
|
puts binary_count_setbits(1024)
|
|
# 1
|
|
|
|
puts binary_count_setbits(1023)
|
|
# 10
|