How to solve a binary gap problem in ruby.
– Counts binary gaps between 1s
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
Write an efficient algorithm for the following assumptions:
n is an integer within the range [1..2,147,483,647].
Solution.
# Using 32 as an example integer
n = 32.to_s(2).to_s
arr = []
n.scan(/(?=1(0+)1)/x) { |m| arr << [m.first, Regexp.last_match.begin(0) + 1] }
arr.map(&:to_s)
e = arr.map { |x| x[0].count "0" }.sort
puts e.empty?
if e.empty?
puts "0"
end
1