Last active
May 6, 2019 17:03
-
-
Save gcasa/042cc457866fc9dcb3351f1425dd7929 to your computer and use it in GitHub Desktop.
Binary Gap Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# you can write to stdout for debugging purposes, e.g. | |
# puts "this is a debug message" | |
def solution(n) | |
# write your code in Ruby 2.2 | |
# puts "Number is #{n}" | |
max = -1 | |
if(n < 0 || n > 2147483647) | |
return max | |
else | |
ones = Array.new | |
bin = n.to_s(2) | |
# puts "binary = #{bin}" | |
(0..bin.length).each do |i| | |
c = bin[i] | |
if c == '1' | |
ones.push i | |
# puts "found 1: #{i} in number" | |
end | |
end | |
if bin.length == ones.length # no gaps... | |
max = 0; | |
elsif ones.length == 1 # only one 1, no gaps... | |
max = 0; | |
else | |
gap = Array.new | |
thestart = 0 | |
theend = 0 | |
(0..ones.length).each do |j| | |
thestart = ones[j] | |
if (j + 1) <= (ones.length - 1) | |
theend = ones[j+1] | |
gap.push (theend - thestart) | |
end | |
end | |
gap.each do |k| | |
if k > max | |
max = k - 1 | |
end | |
end | |
end | |
end | |
return max | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment