user3756502 - 1 year ago 52

Ruby Question

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

`leading_ones(0b11101) # =>3`

leading_ones(0b1111000110) # =>4

Thank you for your effort!

Answer Source

```
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#[].