My reaction isYour solution seems rather complicated. I suggest this,: shift the argument right until it is zero, counting runs of zeros, noting the longest. I hope this is valid C++, I mostly write in C#.
int binary_gap ( unsigned n )
{
int best_gap = 0;
for ( int gap = 0; n != 0; n >>= 1 )
{
if ( ( n & 1 ) == 0 ) gap += 1;
else
{
if ( gap > best_gap ) best_gap = gap;
gap = 0;
}
}
return best_gap;
}