when ever I think of interview, this question always have a JamesBond entry in my mind.
Question:
Given a number, you need to convert it to binary format and then find the maximum no.of zero's between two 1's(binary gap)
Approach:
One among Many
- Convert the number to binary
- Have a loop and find the maximum no.of zero's b/w 1's
1. Convert to binary
1) Well this can be done using basic mathematics(My Approach)
2) Ruby has inbuilt function "to_s(< format >)" for Fixnum(Best, Clear and Easy)
2. Find the BinaryGap of the string
1) My approach was having a loop inside a loop, and iterate over the entire string/array and making it more complex. Yes, its horrible :) and we can do this in a better way.
2) Here, we will be checking the entire string. we decide what to do when 1's and 0's are encountered.
[Note]
FlagVariable is required only when we intentionally pass a binary string starting with zero.
Let me know, if this can be done differently ;)
Thanks for your time.
Top comments (2)
Enumerable in Ruby has a lot of handy methods you may enjoy. In this case we'll want
String#chars
,Enumerable#slice_when
,Enumerable#max_by
, andArray#size
:Now commenting that out to explain what's going on:
each_char
could probably be used here as well.Agree!. Looks even better and understandable