Inspired by this questionquestion I've come up with a solution of my own. The task is to find longest sequence of zeroes surrounded by ones in a binary representations of an integer (e.g. 1041 == 0b10000010001, thus the answer is 5). The task also requires the complexity of \$O(log(N))\$. As far as I understand it means that it means linear complexity in terms of digits, whose number is \$log(N)\$. Am I correct in this conclusion?
private int biggestBinaryGap(int n) {
while (endsWithZero(n))
n >>= 1;
return biggestBinaryGapRec(n >> 1);
}
private int biggestBinaryGapRec(int n) {
if (n == 0)
return 0;
int gap = 0;
for (; endsWithZero(n); n >>= 1, gap++);
return Math.max(gap, biggestBinaryGapRec(n >> 1));
}
private boolean endsWithZero(int n) {
return n > 0 && (n & 1) == 0;
}