Inspired by this question and therefore this one I decided that clearly the best most readable way to solve this is with Regular Expressions.
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.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
I decided to remove the limit of positive numbers only.
Here's the code:
public static int ComputeLargestBinaryGap(int value)
{
var regexp = new Regex("(?<=1)(0+)(?=1)");
var valueAsBinary = Convert.ToString(value, 2);
return
regexp.Matches(valueAsBinary)
.Cast<Match>()
.Select(m => m.Value)
.DefaultIfEmpty(string.Empty)
.Max(s => s.Length);
}
You'll notice that this can be trivially extended to also work for long
or any number representation you can convert to a string binary representation.
I appreciate that's a pretty small amount of code to review but would be intrigued as to whether there's anything I could improve.
For the record, my first actual solution was bit shifting an unsigned int but I stand by the Regular Expression solution.