1
Code ChallengesRuby

Ruby binary gap solution

1 Mins read

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
Related posts
Code ChallengesHow ToProgrammingSoftware

How To Implement Merge Sort and Quick Sort Algorithms In Python 3

3 Mins read
Let’s have a look at how to how to implement merge sort and quick sort algorithms in python 3. One of the…
Automation testingQaRuby

Selenium Ruby Example And Deployment To The Cloud Grid

13 Mins read
Table of contents1 What is Selenium?2 How does Selenium WebDriver in Ruby work?3 How to use Selenium with Ruby?4 How to run…
Code ChallengesProgramming

How To Implement Bubble, Insertion And Selection Sort Algorithms In Python 3

3 Mins read
Table of contents1 Bubble, Insertion and Selection Sort Algorithms In Python 32 Bubble sort Algorithm3 Insertion sort algorithm4 Selection sort Algorithm5 Conclusion…

Leave a Reply

Your email address will not be published. Required fields are marked *

7 + 3 =