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

Don’t miss amazing tips!

1
Related posts
Code ChallengesHow ToProgrammingSoftware

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

3 Mins read
Table of contents0.1 Merge Sort0.2 Quick Sort0.3 Conclusion1 Don’t miss amazing tips! Let’s have a look at how to how to implement…
Automation testingQaRuby

Selenium Ruby Example And Deployment To The Cloud Grid

13 Mins read
Table of contents0.1 What is Selenium?0.2 How does Selenium WebDriver in Ruby work?0.3 How to use Selenium with Ruby?0.4 How to run…
Code ChallengesProgramming

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

3 Mins read
Table of contents0.1 Bubble, Insertion and Selection Sort Algorithms In Python 30.2 Bubble sort Algorithm0.3 Insertion sort algorithm0.4 Selection sort Algorithm0.5 Conclusion1…

Leave a Reply

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

9 + 1 =