Binary Gap

easy bit manipulation

Problem

Given a positive integer n, find the longest distance between any two adjacent 1's in its binary representation. The distance between bits at positions i and j is the absolute value of i − j. If there are not two adjacent 1's, return 0.

Inputn = 22
Output2
22 is 10110; the 1's sit at positions 1, 2, 4 — the largest gap is 4 − 2 = 2.

def binary_gap(n):
    last, best = -1, 0
    i = 0
    while n:
        if n & 1:
            if last != -1:
                best = max(best, i - last)
            last = i
        n >>= 1
        i += 1
    return best
function binaryGap(n) {
  let last = -1, best = 0, i = 0;
  while (n) {
    if (n & 1) {
      if (last !== -1) best = Math.max(best, i - last);
      last = i;
    }
    n >>= 1;
    i++;
  }
  return best;
}
int binaryGap(int n) {
    int last = -1, best = 0, i = 0;
    while (n != 0) {
        if ((n & 1) == 1) {
            if (last != -1) best = Math.max(best, i - last);
            last = i;
        }
        n >>= 1;
        i++;
    }
    return best;
}
int binaryGap(int n) {
    int last = -1, best = 0, i = 0;
    while (n) {
        if (n & 1) {
            if (last != -1) best = max(best, i - last);
            last = i;
        }
        n >>= 1;
        i++;
    }
    return best;
}
Time: O(log n) Space: O(1)