user3756502 user3756502 - 2 months ago 8
Ruby Question

Calculate leading ones in binary depiction of integer in Ruby

I'm searching for a fast function (without strings)

leading_ones(0b11101) # =>3
leading_ones(0b1111000110) # =>4


Thank you for your effort!

Answer
def leading_ones(n)
  nbr = 0
  (n.bit_length-1).downto(0) do |i|
    return nbr if n[i].zero?
    nbr += 1
  end
  nbr
end

leading_ones(6)
  #=> 2

Note 6.to_s(2) #=> "110". This uses the methods Fixnum#bit_length and Fixnum#[].

Comments