C++ Binary Gap
#include <algorithm>
int binaryGap(int n)
{
int gap = 0;
int run = -1; // -1 means no leading '1' has been seen yet
while (n > 0) {
if (n & 1) {
if (run >= 0) {
gap = std::max(gap, run);
}
run = 0;
} else if (run >= 0) {
++run;
}
n >>= 1;
}
return gap;
}
This turns the number into binary, ignores zeroes outside the edges, and finds the longest run of zeroes between 1s.